Tag Archives: i18n

Ruby on Rails Quick Tip: passing variables to i18n localized strings

UPDATE: this tutorial has been updated on May 6th, 2011. Thanks to equivalent.

Hi all,
today I want to share a little gotcha about Ruby on Rails.

I usually embed variables inside my erb (or haml) code in my view to do things like these:

<p>
  Welcome, <%= @user.name %> to our awesome app
</p>

In order to internazionalize my application I needed to pass the username from the view to the localized string.
To do it you have to pass to the translate method an hash with your variable as value and a key to be referenced inside the locale yml file:

<p>
  <%= t("message.welcome", :username => @user.name) %>
</p>

While in the locale yaml file you have to embed the placeholder inside double curly brackets, like this {{variable}}:

en:
  message:
    welcome: "Welcome, %{username} to our awesome app"

Bye and I hope you will find this tip useful,
L