Internationalization Tricks in Rails

Here are some quick tips and tricks I learnt when internationalizing my Rails projects.

Automatically Escaping HTML content
This is probably the most often overlooked feature in Rails’ Internationalization API. You may have come across code snippets like below:

Rails has built in HTML escaping behaviour built into their API when your translation key has the term html

Both the forms below are perfectly valid:

Localizing Pluralized Nouns
Another common use case when translating locale is handling pluralization of certain terms. Instead of writing helpers, we can simply define the translations like so:

And to tell the translator when to use the pluralized forms, we’ll just pass in the count interpolation variable:

Looping Arrays of YML definitions
I’ve built static pages using only translated content and these sometimes comes in repeated patterns. Instead of having unique keys for each of the translated labels, you can actually define these terms like an array pattern.

When rendering your views, you can do this:

Hope these little snippets and tricks will come useful for your projects.

Leave a Reply

Your email address will not be published. Required fields are marked *