Home > Back-end >  Symfony Twig Sandboxing with ArrayLoader
Symfony Twig Sandboxing with ArrayLoader

Time:09-13

My purpose is to sandbox a generated 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 %}"

I'm not able to get any path results from getPath() method. It's empty string.

CodePudding user response:

To sandbox a twig template without using a template file can be done with using chainloader as follows:

Creating a Sandbox Policy:

$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);

To Sandbox a Twig Template without Creating A Twig File:

$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');
  • Related