【问题标题】:Rails 3: Using HTML in i18n form helper translationsRails 3:在 i18n 表单助手翻译中使用 HTML
【发布时间】:2011-05-21 08:04:46
【问题描述】:

我正在使用自动表单标签助手来创建我的表单标签并通过 i18n 支持对其进行翻译,但是,我想在标签中包含 HTML,但我不知道如何使它成为 HTML 安全的。

例如:

en:
  helpers:
    label:
      product:
        name: 'Your Product Name <small>Try to be creative</small>'

最终结果为:

<label for="product_name">Your Product Name &lt;Try to be creative&gt;</label>

但我希望它是:

<label for="product_name">Your Product Name <small>Try to be creative</small></label>

有没有办法让我将翻译指定为 html_safe,这样它就不会在输出之前被编码?

此外,这似乎是设置 HTML 的最语义化方式,但如果我以完全错误的方式处理此问题,我愿意接受建议。

谢谢:)

更新:

<%= form_for @product do |f| %>
  <%= f.label :name %>
  <%= f.text_field :name %>
<% end %>

【问题讨论】:

    标签: ruby-on-rails internationalization html-safe


    【解决方案1】:

    不知道您的实际助手是怎样的,但您可以使用html_safe 轻松做到这一点(前提是您的标签值不会被其他用户输入)。

    类似:t("helpers.label.product.name").html_safe

    如果这不起作用,请给出你的帮助方法的实现,或者只给出输出结果的行。

    ====== 已更新 ======

    感谢您更新的代码,现在我知道最佳答案是什么了:D

    我也不知道你是否真的想要helpers.label.product.name

    但我认为还有另一种方式会更好,它的定义如下:

    en:
      activerecord:
        attributes:
          product:
            labels:
              name: "Your Product Name <small>Try to be creative</small>"
    

    如果您不想构建自己的自定义表单构建器,请使用:

    = f.label :name, Product.human_attribute_name("labels.name").html_safe
    

    其实如果你定义了自己的表单生成器,很容易重新定义标签方法来自动生成它的文本。

    【讨论】:

    • 我正在使用标准的 Rails 助手:api.rubyonrails.org/classes/ActionView/Helpers/…
    • 那么您是在模型上使用吗?你能把你的代码贴在这里吗?
    • 我在原始问题中添加了使用。我只是为模型使用标准的 Rails 表单助手。
    【解决方案2】:

    在 rails3 中使普通键自动成为 html 安全的方法是将 _html 或 .html 附加到键名。例如。名称_html。这只能通过视图中的 translate/t 方法起作用,即不能通过 I18n.t 这无论如何在这里都不起作用,因为标准表单助手不会尝试该版本的密钥。

    创建自己的表单构建器是建议的方式。你也可以这样做

    f.label :name, t('helpers.label.product.name_html')
    

    如果这种情况只发生在几个地方。

    【讨论】:

      【解决方案3】:

      另一种选择是执行以下操作:

          name: '<span>Your Product Name <small>Try to be creative</small></span>'
      

      【讨论】:

        【解决方案4】:

        我用一个新函数解决了这个问题,我把它放在一个帮助文件中:

        def labeltext_with_html(model,field)
          I18n.t("helpers.label.#{model}.#{field}").html_safe
        end
        

        我这样称呼它:

        label(my_model, my_field, labeltext_with_html(my_model, my_field))
        

        只需调整变量以适合您的用例。标签标签可能还需要.html_safe,具体取决于用例。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2014-12-07
          • 1970-01-01
          • 2015-10-27
          • 2011-04-03
          • 2014-12-18
          • 2011-07-27
          • 2011-05-03
          相关资源
          最近更新 更多