Symfony2 HTML in the trans twig filter

16,357

Solution 1

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.

Solution 2

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

Share:
16,357
Mikhail
Author by

Mikhail

CTO at Umbrella-web company Umbrella Web Studio offers you the creation of sharp, up-to-date Web applications with extensible functionality and scalability for high traffic loads. The company offers a wide range of experience in the creation of successful commercial projects.

Updated on June 30, 2022

Comments

  • Mikhail
    Mikhail almost 2 years

    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?

  • Mikhail
    Mikhail over 11 years
    yes, it works. So documentation is wrong when say but static strings are never escaped. Static strings are escaped too.
  • redbirdo
    redbirdo over 11 years
    Hmm, I've only used html in translations where I've been using placeholders in which case the string is by definition not static. You're right that the documentation suggests this example should work without raw, in which case it's a bug, unless you're not using the latest version of Symfony and it's a recent change?
  • Steve Dodier-Lazaro
    Steve Dodier-Lazaro almost 9 years
    And if you had some user data injected in the Twig template, you'd have created a security vulnerability: blog.insight.sensiolabs.com/2013/11/28/…. Moral of the story: do not use raw!
  • redbirdo
    redbirdo almost 9 years
    @SteveDL In my defence, when I wrote this answer the OP's question gave the impression they wanted to translate a static string. I wouldn't agree with 'never use raw' - it has it's uses. For example I've used it on translations I inject start/end anchor tags into, an invaluable use in my opinion, as we needed to keep markup in the twig files. Nevertheless, you are right, I should have said users of 'raw' beware / take care.