Search⌘ K
AI Features

Translating the StoreFront

Explore how to implement internationalization in a Rails 6 application by adding multi-language support through I18n methods. Understand locale configurations, translation keys, and currency formatting to provide a localized storefront experience in English and Spanish. This lesson guides you through translating layouts, buttons, and dynamic content while managing locale parameters and formatting conventions.

Now it’s time to provide the translated text. Let’s start with the layout because it’s pretty visible. We replace any text that needs to be translated with calls to I18n.translate. Not only is this method conveniently aliased as I18n.t, but a helper named t is provided.

Adding translation for the store front

The parameter to the translate function is a unique dot-qualified name. We can choose any name we like, but if we use the t helper function provided, names that start with a dot will first be expanded using the name of the template. So, let’s do that:

HTML
<nav class="side_nav">
<div id="cart" class="carts">
<%= render_if @cart && @cart.line_items.any?, @cart %>
</div>
<ul>
<li><a href="/"><%= t('.home') %></a></li>
<li><a href="/questions"><%= t('.questions') %></a></li>
<li><a href="/news"><%= t('.news') %></a></li>
<li><a href="/contact"><%= t('.contact') %></a></li>
</ul>
<% if session[:user_id] %>
<nav class="logged_in_nav">
<ul>
<li><%= link_to 'Orders', orders_path %></li>
<li><%= link_to 'Products', products_path %></li>
<li><%= link_to 'Users', users_path %></li>
<li><%= button_to 'Logout', logout_path, method: :delete %></li>
</ul>
</nav>
<% end %>
</nav>

Since this view is named layouts/application.html.erb, the English mappings will expand to en.layouts.application. Here’s the corresponding locale file:

YAML
layouts:
application:
title: "The Pragmatic Bookshelf"
home: "Home"
questions: "Questions"
news: "News"
contact: "Contact"

Here it is in Spanish:

YAML
layouts:
application:
title: "Biblioteca de Pragmatic"
home: "Inicio"
questions: "Preguntas"
news: "Noticias"
contact: "Contacto"
...