Adding a link inside translated content in Twig template

后端 未结 4 1553
余生分开走
余生分开走 2021-02-07 00:41

Inside a Twig template I would need to have a translated text that contains a link (the path should be generated by the Router, not statically embedded). Twig does not allow to

4条回答
  •  自闭症患者
    2021-02-07 01:20

    The approach I've taken is this:

    In the translation file:

    page.privacy.policy: Please read our %link_start%privacy policy%link_end%
    

    In the twig file:

    {{ 'page.privacy.policy' | trans({'%link_start%' : '', '%link_end%' : ''}, 'account') | raw }}

    I'm not sure if this can be done using the block syntax you mentioned above as I found it didn't work unless I piped the result of the translation through the 'raw' filter. Also I use message domains to split the translations, hence the 'account' parameter.

    I think the closest to your example would be:

    {{ 'Please read our %link_start%privacy policy%link_end%' | trans({'%link_start%' : '', '%link_end%' : ''}) | raw }}

    EDIT:

    The only issue with this approach I've come across is where I need to programmatically follow a translated link in a unit test as there isn't a single translation representing the link text. Although messy I think it would be possible to get round this by providing a separate translation for the link text and substituting it's translated value into the full text as an additional variable.

提交回复
热议问题