我的目的是將生成的 html 沙箱化。
$loader = new \Twig\Loader\ArrayLoader([
'test1.html.twig' => $this->getMessageObject()->getBody()
]);
$twig = new \Twig\Environment($loader);
$output = "{% sandbox %}{% include ("'.$twig->getLoader()->getSourceContext('test1.html.twig')->getPath().'") %} {% endsandbox %}"
我無法從 getPath() 方法獲得任何路徑結果。它是空字串。
uj5u.com熱心網友回復:
要在不使用模板檔案的情況下對 twig 模板進行沙箱化,可以使用 chainloader 完成,如下所示:
創建沙盒策略:
$tags = ['if'];
$filters = ['filter1', 'filter2'];
$methods = [
'Customer' => ['getCustomer'],
'Person' => ['getPerson']
];
$properties = [];
$functions = ['max'];
$policy = new \Twig\Sandbox\SecurityPolicy($tags, $filters, $methods, $properties, $functions);
$sandbox = new \Twig\Extension\SandboxExtension($policy);
在不創建 Twig 檔案的情況下將 Twig 模板沙箱化:
$loader1 = new \Twig\Loader\ArrayLoader([
'test1.html.twig' => "{% if 1==1 %} Tag Test {%endif%} test content here"
]);
$loader2 = new \Twig\Loader\ArrayLoader([
'sandbox.html.twig' => '{% sandbox %}{% include "test1.html.twig" %} {% endsandbox %}'
]);
$loader = new \Twig\Loader\ChainLoader([$loader1, $loader2]);
$twig = new \Twig\Environment($loader);
$twig->addExtension($sandbox);
$renderedOutput = $twig->render('sandbox.html.twig');
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/507522.html
