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> 
1
  • 2
    {{ var|raw }} was what I was looking for when I found this question via Google. Commented Apr 25, 2014 at 12:46

2 Answers 2

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

See the docs for details.

Sign up to request clarification or add additional context in comments.

4 Comments

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.
By the time I asked the question this wasn't working, but it's better to accept for others looking for answers.
This works great for outputting HTML as entities (e.g. for copy and paste widget examples).
filter has been changed to apply for Twig 3.x: twig.symfony.com/doc/3.x/tags/apply.html
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.

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.