51

I have some translations in my Rails application (config/locale/[en|de].yml) and I use it in my views with <%=t "teasers.welcome" %>. Example:

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

In Rails 2.3.8 this works just fine, with Rails 3, the HTML is escaped and translated to &lt;... How can I prevent this form this translation and use HTML in my translation files like in Rails 2.3.8?

f00860
  • 3,486
  • 7
  • 41
  • 59

2 Answers2

114

Other than using raw, there's an other undocumented (but official) way to do so. All keys ending with _html are automatically rendered unescaped.

Rename the key from

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

to

teasers:
    welcome_html: "<strong>Welcome</strong> to the Website ..."
Simone Carletti
  • 173,507
  • 49
  • 363
  • 364
47

I suppose it's because doing

<%= t("blah") %>

in rails 2.x, now is the equivalent of doing

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

when you're using rails 3.

From the release notes:

Switch to on-by-default XSS escaping for rails.

To fix this, and once again from the release notes:

You no longer need to call h(string) to escape HTML output, it is on by default in all view templates. If you want the unescaped string, call raw(string).

So just replace

<%= t("blah") %>

by

<%= raw t("blah") %>
marcgg
  • 65,020
  • 52
  • 178
  • 231
  • 14
    The convention way is to use keys ending with `_html`. – Simone Carletti Sep 02 '10 at 13:02
  • 4
    Do be careful if you add dynamic data to the translations like using `<%= raw t "welcome", name:user.name %>`. If the user sets the `name` value to some javascript, you're having a XSS attack. – Yoko Dec 14 '16 at 09:28