How to make rails 3 I18n translation automatically safe?

2.8k views Asked by At

I use rails 3. Is there any easy way to tell I18n to respect 'html safness' of string used in interpolation and make all translated string html safe by default? So if I have this en.yml:

en:
  user_with_name: 'User with name <em>%{name}</em>'

and I use t('user_with_name', :name => @user.name), I get users name html escaped, but <em> and </em> is left as is?

3

There are 3 answers

4
Anthony Alberto On BEST ANSWER

Old question, but if someone wants to achieve this, here's the monkey patch I came up with :

module ActionView
  module Helpers
    module TranslationHelper
      private
      def html_safe_translation_key?(key)
        true
      end
    end
  end
end

Put this in an initializers and that's it! Works with Rails 3.2.6. Only marks the text in localization files as safe, not the interpolation parameters.

1
user444349 On

Change the name from user_with_name to user_with_name_html, then rails will know you have included html in the text.

1
onurozgurozkan On

http://guides.rubyonrails.org/i18n.html#using-safe-html-translations

The official Rails guide says you can use the interpolated variables without concern, since they are html escaped automatically, unless you specifically declare them to be String.html_safe.

From the guide:

Interpolation escapes as needed though. For example, given:

en:
  welcome_html: "<b>Welcome %{username}!</b>"

you can safely pass the username as set by the user:

<%# This is safe, it is going to be escaped if needed. %>
<%= t('welcome_html', username: @current_user.username %>

Safe strings on the other hand are interpolated verbatim.