New in Symfony 8.2: Safer HTML in Translations
Contributed by Hugo Alliaume in #66690…
Contributed by Hugo Alliaume in #66690
Sometimes, a translated message needs some HTML inside it, such as a link in the middle of a sentence. The usual solution is to put the HTML in the translation and render it with the raw filter:
{# translations/messages.en.yaml:
auth_prompt: 'Please <a href="/login">sign in</a> to continue.' #}
{{ 'auth_prompt'|trans|raw }}
This has several problems: URLs are hardcoded in the translation files, any HTML added by translators is rendered as is, and the message parameters are no longer escaped. If one of them contains user input, you have an XSS vulnerability.
The trans_html Filter
Symfony 8.2 adds a trans_html Twig filter to solve this. Translations no longer contain real HTML, but pseudo-tags (<name>...</name>) without attributes:
# translations/messages+intl-icu.en.yaml
auth_prompt: 'Hi {name}! Please <signin_link>sign in</signin_link> or <signup_link>create an account</signup_link>.'
In the template, you map each pseudo-tag to the HTML element to render. Elements are defined as data (the tag name and its attributes), and you can pass a list of elements to nest them (from the outermost to the innermost):