16
votes

I use the Symfony2.1 and have the default config.yml

Documentation said:

  {# but static strings are never escaped #}
  {{ '<h3>foo</h3>'|trans }}

But if I copy and paste it into the my empty template (without any additional autoescapes or another) I got the escaped string <h3>foo</h3>. What I do wrong?

2
I've provided an answer but I was wondering why you would want to do this in practice as if you wanted to change the markup you'd need to update all your translation keys. Or is this a simplified example and you're really injecting the html into the translation using message placeholders? - redbirdo
Yes it's a simplified example. In real life I want to inject a variable between tags: {{ 'Hello <strong>%var%</strong>'|trans({'%var%' : var}) }}. Now to do this I have to write: {{ 'Hello <strong>%var%</strong>'|trans({'%var%' : var|e})|raw }} - Mikhail

2 Answers

19
votes

Try it with the twig raw filter:

{{ '<h3>foo</h3>' | trans | raw }}

However, do not use the raw filter if you are processing any user input! It allows for cross-site-scripting attacks, according to the creators of Symfony. See this similar question for a secure but more tedious alternative.

2
votes

Holding HTML stuff in translations is wrong, because translators usually break it. But if you really need it:

{% trans %}<h3>foo</h3>{% endtrans %}

https://github.com/symfony/symfony/issues/2713#issuecomment-12510417