Search code examples
ruby-on-railsinternationalizationhtml-safe

Rails 3: Using HTML in i18n form helper translations


I am using the automatic form label helper for creating my form labels and having them translated via the i18n support, however, I want to have HTML in the label and I can't figure out how to make it HTML safe.

For example:

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

Ends up as:

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

But I want it to be:

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

Is there a way for me to specify the translation as html_safe so that it doesn't get encoded before the output?

Also, this seems like the most semantic way for the HTML to be setup but I am open to suggestions if I am approaching this entirely the wrong way.

Thanks :)

Updated:

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

Solution

  • Don't know how your actual helper is, but you could use html_safe to do that easily (provided that your label's value won't be input by other users).

    something like: t("helpers.label.product.name").html_safe

    If this is not working, please give your implementation of your helper method, or only the lines for outputting the result.

    ====== UPDATED ======

    Thanks to your updated code, now I know what's the best answer :D

    I don't know too if you really want helpers.label.product.name.

    But there is another way I think would be better, which is define as he following:

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

    If you don't want to build your own custom form builder, use this:

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

    Actually if you define your own form builder, it easy redefine the label method to generate it's text automatically.