Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 %>
like image 276
Jeremy Baker Avatar asked Dec 07 '10 01:12

Jeremy Baker


2 Answers

The way to make a normal key automatically html safe in rails3 is to append _html or .html to the key name. E.g. name_html. This only works via the translate/t method in the view, i.e. not via I18n.t This isn't going to work here anyway though as the standard form helper doesn't try that version of the key.

Creating your own form builder is the way to go as suggested. You could also do

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

If this only happens in a couple of places.

like image 50
chrismcg Avatar answered Oct 17 '22 15:10

chrismcg


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.

like image 45
PeterWong Avatar answered Oct 17 '22 16:10

PeterWong