Symfony2: HTML inside translation message

后端 未结 9 1758
醉话见心
醉话见心 2020-12-09 02:12

In messages.en.yml, I have

confirmed: Congrats %username%, your account is now activated.

But I want to \'bold\' username to

相关标签:
9条回答
  • 2020-12-09 02:29

    In my opinion, this is the best solution today:

    'key'|trans({'%username%': '<strong>' ~ suspiciousVar|escape ~ '</strong>'})|raw
    

    The only risk here is stored XSS in your translation files.

    0 讨论(0)
  • 2020-12-09 02:34

    Twig's Raw Filter

    I don't know if this was an option back in 2013 but when using translation, you can apply the raw twig filter having this translation string:

    confirmed: Congrats <span class='bold'>%username%</span>, 
               your account is now activated.
    

    And use it in twig like this:

     {{ 'confirmed'|trans|raw }}
    

    This will not escape the html inside the string and will display the username as bold.

    Update: I haven't seen the comment the first time, but Rvanlaak had proposed the raw filter solution in the first place.

    Security issues

    Note that the content of those translation strings must not be user provided, because it could open up your application to XSS attacks. Using the raw filter allows JavaScript to be executed if a malicious user is able to input custom data into the translation strings (Community based translations for example)

    Separation of concerns

    Using the raw filter does not comply with separation of concerns as the content and styling are bound together. As Ferhad mentioned, using his method, separation of concern will be maintained. But in my case, I preferred using a simple raw filter. I felt that for my case, Ferhad's method was a bit overkill for me, though it would be more recommended his way

    0 讨论(0)
  • 2020-12-09 02:36

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

    Twig:

    {% trans %}confirmed{% endtrans %}
    

    Yaml translation file:

    confirmed: 'Congrats <span class="bold">%username%</span>, your account is now activated.'
    

    Discussion about this: https://github.com/symfony/symfony/issues/2713

    0 讨论(0)
提交回复
热议问题