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

  • http://eq8.eu equivalent

    welcome: “welcome %{username} to this …”

    …oh and newer use :default or :scope as placeholder

    • http://lucatironi.net Luca Tironi

      You’re right. Just after I wrote this it happened to me to discover that they changed the markup, but I never resolved to change the quick tip. Thanks for the input.

  • http://www.noteng.com Paul Emico

    Great tip …

    Thanks a lot.

  • Ruby developer

    Thank you! Great work.

  • Dan

    Thanks!

  • German

    Just what i was looking for, thanks :)

  • JWheaton

    Thanks, that helped a lot!

  • Abibulluah

    Thanks.

  • http://www.facebook.com/bean.winchester Bean Winchester

    Nice! Thanks!! Briefly and clearly! You`re the man!

  • Guilherme

    Thanks!