September 25, 2015

JavaScript localization in Ruby on Rails

Localization (or internationalization) in Rails is easy. But there is no built in support for JavaScript localization. Luckily it is very easy to implement it.

1) Add your translations to the locale file under the javascript section.

# config/locales/en.yml
    hello: Hello World!

2) Include it into the <head> section of your layout.

# app/views/layouts/application.html.erb
<%= javascript_tag do %>
  window.I18n = <%= t('javascript').to_json.html_safe %>
<% end %>

3) Use it in your JavaScript files.

// app/assets/javascripts/hello_world.js
$(function() {

Hey there!

My name is Patrik Bóna and I am the only programmer at Memberful. This blog is kind of dead, but I just started my own Ruby on Rails screencast. Follow me on Twitter if you want to be notified about my newest videos.