6

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?

tig
  • 25,841
  • 10
  • 64
  • 96

3 Answers3

6

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.

Magne
  • 16,401
  • 10
  • 68
  • 88
onurozgurozkan
  • 1,654
  • 1
  • 21
  • 32
  • This should be the accepted answer, as it is correct, and the simplest way of solving the problem. – Magne Feb 05 '15 at 10:02
5

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

GDP
  • 8,109
  • 6
  • 45
  • 82
user444349
  • 51
  • 1
  • 2
    I know about this way, but this is a very bad way: 1) It does not sanitize intepolation params, so any way I should do this, or I can get into trobles 2) I need to add this prefix 3) As I am writing all xxx.ymls, than I know what is in there, so why use prefix at all?? 4) I want this to work automatically! – tig Apr 01 '11 at 13:04
2

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.

Anthony Alberto
  • 10,325
  • 3
  • 34
  • 38