【问题标题】:Use HTML inside a Rails translation file在 Rails 翻译文件中使用 HTML
【发布时间】:2011-04-07 06:20:02
【问题描述】:

我在我的 Rails 应用程序 (config/locale/[en|de].yml) 中有一些翻译,我在 <%=t "teasers.welcome" %> 的视图中使用它。示例:

teasers:
    welcome: "<strong>Welcome</strong> to the Website ..."

在 Rails 2.3.8 中,这工作得很好,在 Rails 3 中,HTML 被转义并翻译为 &amp;lt;... 我怎样才能防止这种形式的这种翻译,并在我的翻译文件中使用 HTML,就像在 Rails 2.3 中一样。 8?

【问题讨论】:

    标签: html ruby-on-rails localization translation


    【解决方案1】:

    除了使用raw,还有另一种未记录(但官方)的方法。 所有以_html 结尾的键都会自动呈现为非转义。

    重命名密钥来自

    teasers:
        welcome: "<strong>Welcome</strong> to the Website ..."
    

    teasers:
        welcome_html: "<strong>Welcome</strong> to the Website ..."
    

    【讨论】:

    【解决方案2】:

    我想是因为做

    <%= t("blah") %>
    

    在 rails 2.x 中,现在相当于做

    <%=h t("blah") %>
    

    当您使用 Rails 3 时。

    来自release notes:

    切换到默认开启 XSS 转义 用于导轨。

    要解决此问题,请再次参考发行说明:

    你不再需要调用 h(string) 要转义 HTML 输出,它由 所有视图模板中的默认值。如果你 想要未转义的字符串,请致电 原始(字符串)。

    所以替换

    <%= t("blah") %>
    

    <%= raw t("blah") %>
    

    【讨论】:

    • 非常感谢您的回答!
    • 约定方式是使用以_html结尾的键。
    • 如果您将动态数据添加到翻译中,例如使用&lt;%= raw t "welcome", name:user.name %&gt;,请务必小心。如果用户将name 值设置为某个 javascript,则说明您遇到了 XSS 攻击。
    猜你喜欢
    • 2016-01-10
    • 1970-01-01
    • 1970-01-01
    • 2011-05-21
    • 1970-01-01
    • 1970-01-01
    • 2018-08-31
    • 2023-03-27
    • 1970-01-01
    相关资源
    最近更新 更多