在messages.en.yml,我有
confirmed: Congrats %username%, your account is now activated.
Run Code Online (Sandbox Code Playgroud)
但我想用'粗体'用户名示例......我怎么能做到这一点?
confirmed: Congrats <span class='bold'>%username%</span>, your account is now activated.
Run Code Online (Sandbox Code Playgroud)
当然我可以在这个例子中使用两个句子
first: Congrats
second: , your account ...
Run Code Online (Sandbox Code Playgroud)
和twig内部使用html标签,但这看起来很脏.
sef*_*rov 24
在这种情况下,我开始使用这样的:
confirmed: Congrats %start_link%%username%%end_link%, your account is now activated
Run Code Online (Sandbox Code Playgroud)
由于保持关注点分离,强烈建议采用这种方式.
在YAML中,我使用了这样的翻译没有任何问题:
trans.key: click <a href="%url%">here</a> to continue
Run Code Online (Sandbox Code Playgroud)
虽然翻译和设计应该保持分离,但总有一些情况你必须在翻译文件中使用html标签,因为它也可以在像Facebook和Twitter这样的大型项目中看到.
在这种情况下,您可以使用Symfony 推荐的XLIFF格式.内翻译文件:
<trans-unit id="1">
<source>confirmed</source>
<target>Congrats <![CDATA[<span class='bold'>%username%</span>]]> , your account is now activated.</target>
</trans-unit>
Run Code Online (Sandbox Code Playgroud)
我不知道这是否是2013年的一个选项,但是当使用翻译时,您可以应用具有此翻译字符串的原始树枝过滤器:
confirmed: Congrats <span class='bold'>%username%</span>,
your account is now activated.
Run Code Online (Sandbox Code Playgroud)
并在像这样的树枝中使用它:
{{ 'confirmed'|trans|raw }}
Run Code Online (Sandbox Code Playgroud)
这不会转义字符串中的html,并将用户名显示为粗体.
更新:我没有第一次看到评论,但Rvanlaak首先提出了原始过滤解决方案.
请注意,这些翻译字符串的内容不得由用户提供,因为它可能会将您的应用程序打开以进行XSS攻击.如果恶意用户能够将自定义数据输入到翻译字符串(例如,基于社区的翻译),则使用原始过滤器可以执行JavaScript
由于内容和样式绑定在一起,因此使用原始过滤器不符合关注点的分离.正如Ferhad所说,使用他的方法,将保持关注点的分离.但就我而言,我更喜欢使用简单的原始过滤器.我觉得,对于我的情况,Ferhad的方法对我来说有点矫枉过正,尽管他的方式会更加推荐
我的方法虽然仍然很难看,但至少尊重关注点的分离.转义过滤器用于转义变量,使得最终结果在XSS中非常安全,因为所有其他来源都被认为是硬编码的.
translations.yml
points: You have %num% points left.
Run Code Online (Sandbox Code Playgroud)template.html.twig
{% set pointsFormatted = '<span class="points">' ~ num | escape ~ '</span>' %}
{{ 'pages.score.points' | trans({'%num%' : pointsFormatted}) | raw }}
Run Code Online (Sandbox Code Playgroud)