Search⌘ K
AI Features

Adding a Locale Switcher

Explore how to implement a user-friendly locale switcher in a Rails application. Learn to use form tags, JavaScript, and CSS to let users change the interface language seamlessly, ensuring accessibility whether JavaScript is enabled or not.

Making translation user friendly

We’ve completed the task, but we need to advertise its availability more. There are some unused areas on the top-right side of the layout. Let’s add a form immediately before the image_tag in line 10:

HTML
<header class="main">
<aside>
<%= form_tag store_index_path, class: 'locale' do %>
<%= select_tag 'set_locale',
options_for_select(LANGUAGES, I18n.locale.to_s),
onchange: 'this.form.submit()' %>
<%= submit_tag 'submit', id: "submit_locale_change" %>
<% end %>
</aside>
<%= image_tag 'logo.svg', alt: 'The Pragmatic Bookshelf' %>
<h1><%= @page_title %></h1>
</header>

The form_tag in line 3 specifies the path to the store as the page to be redisplayed when the form is submitted. A class attribute lets us associate the form with some CSS.

The ...