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:
1 2 3 | article: title: "This is my title" description: "This is <strong>HTML</strong> content" |
1 | <%= t("article.description").html_safe %> |
Rails has built in HTML escaping behaviour built into their API when your translation key has the term html
1 2 3 4 5 6 7 8 | article: title: "This is my title" description_html: "This is <strong>HTML</strong> content" article: title: "This is my title" description: html: "This is <strong>HTML</strong> content" |
Both the forms below are perfectly valid:
1 2 | <%= t("article.description_html") %> <%= t("article.description.html") %> |
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:
1 2 3 | pokemon: one: "Pokemon" other: "Pokemons" |
And to tell the translator when to use the pluralized forms, we’ll just pass in the count interpolation variable:
1 | <%= t(".pokemon", count: 2 %> |
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.
1 2 3 4 5 | pokemons: - name: "Pikachu" description: "Whenever Pikachu comes across something new, it blasts it with a jolt of electricity." - name: "Magikarp" description: "Magikarp is a pathetic excuse for a Pokémon that is only capable of flopping and splashing." |
When rendering your views, you can do this:
1 2 3 4 | <% t(".pokedex.pokemons").each do |pokemon| %> <%= pokemon[:name] %> <%= pokemon[:description] %> <% end %> |
Hope these little snippets and tricks will come useful for your projects.