8

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>
clami219
  • 2,958
  • 1
  • 31
  • 45
vik
  • 762
  • 1
  • 7
  • 18
  • 2
    [`{{ var|raw }}`](http://twig.sensiolabs.org/doc/filters/raw.html) was what I was looking for when I found this question via Google. – Martin Thoma Apr 25 '14 at 12:46

2 Answers2

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

See the docs for details.

Elnur Abdurrakhimov
  • 44,533
  • 10
  • 148
  • 133
  • That might be correct. The docs were updated since then. I'm glad my solution worked and I don't have to work with Symfony2 anymore. Thank you. Maybe somebody else can try. I'll forward it to the team and they might refactor it. – vik May 20 '12 at 21:00
  • By the time I asked the question this wasn't working, but it's better to accept for others looking for answers. – vik Jun 27 '12 at 22:59
  • This works great for outputting HTML as entities (e.g. for copy and paste widget examples). – Steve Oct 30 '12 at 11:53
  • 5
    `filter` has been changed to `apply` for Twig 3.x: https://twig.symfony.com/doc/3.x/tags/apply.html – Egon Olieux Jan 15 '20 at 05:26
2

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.

Andresch Serj
  • 35,217
  • 15
  • 59
  • 101
  • 2
    `The source function returns the content of a template without rendering it` - as I understand, this does not render twig. `|raw` is not for rendering or not rendering twig, it's about output escaping. – Marius Balčytis Apr 28 '15 at 06:41