Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2: HTML inside translation message

Tags:

symfony

In messages.en.yml, I have

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

But I want to 'bold' username to example ... how can I made this ?

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

Of course I could use two sentence in this example like

first: Congrats second: , your account ...  

and inside twig use the html tag but this seems very dirty.

like image 350
Lukas Lukac Avatar asked Feb 15 '13 09:02

Lukas Lukac


2 Answers

Update 2

In such cases, I started to use like this:

confirmed: Congrats %start_link%%username%%end_link%, your account is now activated 

Since separation of concerns is maintained, this way is strongly recommended.


Update

In YAML, I have used translations like this without any problem:

trans.key: click <a href="%url%">here</a> to continue 

Although translations and design should be kept separated there are always some situations that you must use html tags inside translation files as it is also seen in huge projects like Facebook and Twitter.

In such situations, you can use XLIFF format which is being recommended by Symfony. Inside translation file:

<trans-unit id="1">    <source>confirmed</source>    <target>Congrats <![CDATA[<span class='bold'>%username%</span>]]> , your account is now activated.</target> </trans-unit> 
like image 154
seferov Avatar answered Oct 01 '22 04:10

seferov


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

like image 20
Lunfel Avatar answered Oct 01 '22 03:10

Lunfel