Avoid html escaping I18n strings in Rails 3

Update: Be careful with this method, if you have string-interpolation with user input. It might be the cause of XSS. I’ll cough up a better method, that can handle cases with and without interpolation

With Rails 3 comes a shift in who is responsible for escaping output. You no longer need to write <%= h(@some_value)%>, Rails will automatically escape every string unless you mark it html-safe.

Unfortunately this also goes for I18n strings. In my case I have a lot of strings containing HTML entities like &oslash; which is now escaped by Rails when I write <%=t(:some_key)%> and therefore “Søg” is now displayed as “S&oslash;g”. Not good.

A tiny fix for this:

module I18n
  class << self
    alias :prev_translate :translate
    def translate(*args)
      prev_translate(*args).html_safe
    end
  end
end

This ensures that I18n output is marked as html-safe. Just place it as a initializer and your translations will work as before.

Skriv et svar

Din e-mailadresse vil ikke blive offentliggjort. Krævede felter er markeret med *