如何使 Rails 3 I18n 自动翻译安全?
我使用rails 3。有没有什么简单的方法可以告诉I18n尊重插值中使用的字符串的“html安全性”并使所有翻译的字符串默认为html安全?因此,如果我有这个 en.yml
:
en:
user_with_name: 'User with name <em>%{name}</em>'
并且我使用 t('user_with_name', :name => @user.name)
,我会得到用户名 html 转义,但 和
保持原样?
I use rails 3. Is there any easy way to tell I18n to respect 'html safness' of string used in interpolation and make all translated string html safe by default? So if I have this en.yml
:
en:
user_with_name: 'User with name <em>%{name}</em>'
and I use t('user_with_name', :name => @user.name)
, I get users name html escaped, but <em>
and </em>
is left as is?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
http://guides.rubyonrails.org/i18n.html#using-safe -html-translations
官方 Rails 指南说你可以不用担心地使用插值变量,因为它们是 html 自动转义的,除非你特别声明它们是 String.html_safe。
根据指南:
插值会根据需要转义。例如,给定:
您可以安全地传递用户设置的用户名:
另一方面,安全字符串是逐字插入的。
http://guides.rubyonrails.org/i18n.html#using-safe-html-translations
The official Rails guide says you can use the interpolated variables without concern, since they are html escaped automatically, unless you specifically declare them to be String.html_safe.
From the guide:
Interpolation escapes as needed though. For example, given:
you can safely pass the username as set by the user:
Safe strings on the other hand are interpolated verbatim.
将名称从
user_with_name
更改为user_with_name_html
,然后 Rails 就会知道您在文本中包含了 html。Change the name from
user_with_name
touser_with_name_html
, then rails will know you have included html in the text.老问题,但如果有人想实现这一点,这是我想出的猴子补丁:
将其放入初始化器中,就是这样!
适用于 Rails 3.2.6。
仅将本地化文件中的文本标记为安全,而不将插值参数标记为安全。
Old question, but if someone wants to achieve this, here's the monkey patch I came up with :
Put this in an initializers and that's it!
Works with Rails 3.2.6.
Only marks the text in localization files as safe, not the interpolation parameters.