How to use Rails I18n fallback key in conjunction with parameter list?

When using I18n rails API, you will most likely find examples of how to use parameter lists to the translation API.

For e.g.

If you have the following entry in your en.yml
          en:
               test_message_specific: "This is a specific test message for user %{user}"

Now if you have to use this key along with a parameter, you will most likely specify

I18n.t("test_message_specific", user: "Bob")

If you want to use a default key if the specified key is not available, again the API provides clear examples for this case:

E.g.

  en:
       test_message_specific: "This is a specific test message"
       test_message_default "This is a default test message"

We will then translate as follows:

I18n.t("test_message_specific", default: t("test_message_default"))

But what if we want to have both, i.e. parameter lists and default key as well, with both the specified key and default key needing same number of parameters? At least I could not find clear examples for this case from the API but it does support this. Now when will you need this? Let's say, you have a key whose value has to be overridden for say a few cases (say a few countries where the application is used), but for most other cases you want to use a default key, wouldn't it be easy if we are able to declare just as many custom keys instead of many repeated keys even for countries that don't need customisation?

E.g. if our application is used in US, UK, and Canada (this list is small but you will really feel the pinch if you have a long list and had to duplicate the same key for every case unless Rails I18n API provided this feature), and let's say we want to override only for Canada, then we can simply declare only two keys,

e.g.
      en: 
          test_message_default: "This is the default test message for %{user}"
          test_message_ca: "This is the canadian test message for %{user}"

Now let's see how to use the I18n API with these keys:

I18n.t("test_message_"+@country, default: I18n.t("test_message_default"), user: @user)

and ....

Voila! It works! When country is CA, it uses Canadian message and substitutes the "user" parameter, else it uses the default message, but still substitutes the parameter.


PS: Please leave your comment on this post (as long as it is not abusive ;)), as it will help me understand the usefulness.

Related Articles

0 comments:

Post a Comment

Blog Archive

Powered by Blogger.

Followers