在 Twig 模板的翻译内容中添加链接 [英] Adding a link inside translated content in Twig template
问题描述
在 Twig 模板中,我需要一个包含链接的翻译文本(路径应该由路由器生成,而不是静态嵌入).Twig 不允许在 trans 块内呈现变量 - 我也知道以下几点:
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 render a variable inside a trans block - I'm also aware of the following:
{% trans with {'%name%': 'Fabien'} from "app" %}
Hello %name%
{% endtrans %}
但我不知道如何使用它在翻译中注入这样的片段
but I can't see how to use that to inject inside the translation a piece like this
<a href="{{ path('privacy') }}">privacy policy</a>
(当然,锚文本也要翻译)
(of course, the anchor text should be translated as well)
推荐答案
我采取的方法是这样的:
The approach I've taken is this:
在翻译文件中:
page.privacy.policy: Please read our %link_start%privacy policy%link_end%
在树枝文件中:
<p>{{ 'page.privacy.policy' | trans({'%link_start%' : '<a href="'~path('privacy-policy')~'">', '%link_end%' : '</a>'}, 'account') | raw }}</p>
我不确定这是否可以使用你上面提到的块语法来完成,因为我发现它不起作用,除非我通过原始"过滤器传输翻译结果.此外,我使用消息域来拆分翻译,因此使用帐户"参数.
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:
<p>{{ 'Please read our %link_start%privacy policy%link_end%' | trans({'%link_start%' : '<a href="'~path('privacy-policy')~'">', '%link_end%' : '</a>'}) | raw }}</p>
我遇到的这种方法的唯一问题是我需要在单元测试中以编程方式跟踪翻译的链接,因为没有表示链接文本的单个翻译.虽然很乱,但我认为可以通过为链接文本提供单独的翻译并将其翻译值作为附加变量替换为全文来解决这个问题.
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.
这篇关于在 Twig 模板的翻译内容中添加链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!