Fork me on GitHub

Keith Pitt

Hi! I'm Keith. I'm a Melbourne based Web/iOS Developer. I am the author of VendorKit and DesksNear.Me. Outside of code, I watch scary movies, perform illusions, and enjoy stand up comedy.

Contact Me

“Lazy” Lookup Translations

Friday, January 21, 2011

A feature that so many people seem to not know about the I18n API is the ability to lookup translations using a short “dot” syntax.

For example, say we are in a view located at: app/views/books/index/title

The view would look something like this:

<h1><%= t 'books.index.title' %></h1>
<p><%= t 'books.index.intro' %></p>
 
<ul>
  <li><%= t 'books.index.point1' %></li>
  <li><%= t 'books.index.point1' %></li>
  <li><%= t 'books.index.point1' %></li>
</ul>

As you can see, we are repeating books.index quite a bit. Using this syntax will also make refactoring more cumbersome if we decide to move this view to another folder.

Rails provides us with a way to fix this. Under the “Organization of Locale Files” section of the I18n Rails Guide, it describes a “lazy” lookup for translations. Instead of having to put books.index at the start of each translation lookup, we can just use a dot. By using the dot, the view will automatically look at this views position in the application, and use that as the scope. So if you have a file located at: app/views/posts/comments/index the scope for translations of that file will be: posts.comments.index. Pretty cool huh?

Using this new syntax, we can clean up the above view like so:

<h1><%= t '.title' %></h1>
<p><%= t '.intro' %></p>
 
<ul>
  <li><%= t '.point1' %></li>
  <li><%= t '.point1' %></li>
  <li><%= t '.point1' %></li>
</ul>

This is a really nice and DRY way of inserting translations into your application.