October 6, 2011

Asset Pipeline and I18n using jQuery-localize

After last months Frozenrails conference I tried to replicate the goals of Jeff Casimirs “Blow Up Your Views” talk using the Rails Asset Pipeline. The first step was using HAML and Handlebars in the asset pipeline to have most ActionView Helpers at your disposal. There was only one problem I did not address at all in my last post, localization.

At work I talked a lot with Marc Schwering (@dgAlien) about this; separating views, data-models and localization looks like a good solution to us.

The views are handled using HAML and all ActionView Helpers are available, leaving the following steps to reach our goal:

  • overwriting haml_assets ActionView translate method, to keep things simple
    • the localization takes place at compile time using I18n.default_locale
    • the result is wrapped into a span-tag, with an appropriate rel-attribute to support jQuery-localize
  • serve all available locales using a Rails Engine

The Rails Engine, which also hooks into haml_assets, is available at Github. Here’s a small example on how to use this:

Setup: update your Gemfile & install dependencies

# haml, haml_assets and handlebars_assets dependencies
gem 'tilt'
gem 'execjs', :git => 'git://github.com/sstephenson/execjs.git'
gem 'ejs'

gem 'haml', :git => 'https://github.com/infbio/haml.git', :branch => 'form_for_fix'
gem 'haml_assets', git: 'https://github.com/infbio/haml_assets.git'
gem 'handlebars_assets'

# localization engine
gem 'jquery-localization-engine', git: 'https://github.com/nicolai86/jquery-localization-engine.git'

Run bundle install to install the new dependencies. Next, follow the installation instructions for haml_assets and handlebars_assets.

Make sure to install jQuery-localize as well!

Create a sample view

Inside app/assets/templates create an app folder and index.jst.hbs.haml inside. Its content could look like this:

.header
  = t :hello

.locales
  - I18n.available_locales.each do |locale|
    = link_to_function locale, "localize('#{locale}')"

Some important things to note:

  • you can use standard t and translate methods just like you’re used to
  • when using translation, the keys will be localized using the I18n.default_locale
  • context-dependent localizations, like ${name} won’t work since we have no context!

Add jQuery-localize

Inside your application.coffee:

$ ->
  # load index view
  $("#container").append JST["app/index"]()

window.localize = (locale) ->
  $("[rel*=localize]").localize("locales/#{locale}",{ language: locale })
  false

As you can see I’m using standard jQuery-localize to localize the index page. So there you are: you can now localize views which reside entirely in the asset pipeline. No black magic involved.

Happy hacking!

© Raphael Randschau 2010 - 2022 | Impressum