zargony.com

#![desc = "Random thoughts of a software engineer"]

How to use i18n string interpolation

Since Rails 2.2 has been released last week, lots of people are beginning to translate their applications -- or, at least, many people seem to prepare their applications for later translation by replacing strings in views with t() calls.

If you're modifying your application to be i18n-ready, or if you're creating a new multilingual application, here's a useful guideline to remember: translate meanings, not words.

Remember, that other languages are not just only different words -- most often, sentences are build differently in other languages. An application should be able to output correct sentences in every supported language; therefore you need to translate meanings, not just strings.

Bad example

_article_info.html.erb:

<%= t('article.posted_by') %> <%= @article.author %> <%= t('article.on') %> <%= @article.created_at.to_s %>

config/locales/en.yml:

en:
  article:
    posted_by: "Posted by"
    on: "on"

In this example, simply the strings are translated, which leads to 2 problems:

  1. A translator (who typically only gets the translation files, but not the views) cannot recognize the meaning of the sentence. In this example, it may be obvious that "on" refers to "posted by", but generally a translation of "on" cannot be done without knowing the context. So the meaning is hidden from the translator here, because he'd need to see the view file to understand the sentence.
  2. The sentence order is fixed to "posted by" + name + "on" + date. While this is perfectly fine for English, other languages may need a completely different sentence order.

Good example

_article_info.html.erb:

<%= t('article.postinfo', :author => @article.author, :date => @article.created_at.to_s) %>

config/locales/en.yml:

en:
  article:
    postinfo: "Posted by {{author}} on {{date}}"

Here, the translation uses string interpolation to put variable values into a meaningful sentence. The translation string itself is a complete sentence with a recognizable sense (i.e. it can be translated easily) and the given variables could be put at any place within the string, allowing arbitrary sentence order. A German translation could look like:

config/locales/de.yml:

de:
  article:
    postinfo: "Geschrieben am {{date}} von {{author}}"

Keeping this in mind while writing i18n-enabled views will save you a lot of trouble if you add more translations later.