Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make rails 3 I18n translation automatically safe?

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?

like image 342
tig Avatar asked Mar 31 '11 15:03

tig


1 Answers

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.

like image 69
onurozgurozkan Avatar answered Sep 28 '22 08:09

onurozgurozkan