Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

raw or escape on include in twig

Tags:

php

twig

symfony

I would like to escape a file, which I'm including

following code won't escape the html tags in file "_custom_plugin_script.html.twig". Is there another way?

<pre>
    {% autoescape true %}
        {% include "_custom_plugin_script.html.twig" | raw %}
    {% endautoescape %}
</pre>

After a couple days, I have found a workaround, but not an answer. So first raw would not escape therefore I should use escape. However raw and escape won't work within {% %} but in {{}}.

So here comes the workaround

Content of the Action

$customPluginScript = $app['twig']->render('_custom_plugin_script.html.twig', array(
    'data' => $data,
));


return $app['twig']->render('confirm.html.twig', array(
    'data' => $data,
    'customPluginScript' => $customPluginScript
));

And the a part of confirm.html.twig

<script>
// don't escape content of customPluginScript
  {{ customPluginScript | raw }}
</script>


<!-- escape content of customPluginScript -->
<pre>
  {{ customPluginScript }}
</pre>
like image 593
vik Avatar asked Mar 09 '12 10:03

vik


2 Answers

{% filter escape %}
    {% include '...' %}
{% endfilter %}

See the docs for details.

like image 57
Elnur Abdurrakhimov Avatar answered Sep 27 '22 19:09

Elnur Abdurrakhimov


As this is the first result that comes up when googling for twig include raw it's worth mentioning that twig now supports this with the following syntax

{{ source('AcmeSomeBundle:Default:_custom_plugin_script.html.twig') }}

However, this does not render the template as mentioned by barius.

like image 43
Nigel Angel Avatar answered Sep 27 '22 21:09

Nigel Angel