Repository is archived
No commit activity in last 3 years
No release in over 3 years
I18next and dynamic localization for your Rails 3.2 asset pipeline
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
 Dependencies

Development

Runtime

< 5.0, >= 3.2.16
 Project Readme

RailsAssetLocalization

Gem Version Build Status

A Rails Engine that allows you to use i18next with the asset pipeline. Locales are served dynamically to allow easy integration with services like CopyCopter.

Basic Setup

Add this to your Gemfile:

gem 'rails-asset-localization', git: 'git@github.com:nicolai86/rails-asset-localization.git', branch: :master

and this to your routes:

mount RailsAssetLocalization::Engine => "/locales"

Your locales are now available under /locales/:locale

Now you need to load i18next:

# inside your application.coffee
#= require i18next.min # or i18next for development version

and properly configure it to work with your rails locales:

# inside your app startup code
locale = "de"
i18n.init({
  # change default interpolation from __VARIABLE__ to rails-style %{VARIABLE}
  interpolationPrefix: '%{'
  interpolationSuffix: '}'

  # current locale to load
  lng: locale

  # rails-asset-localization path
  resGetPath: '/locales/%{lng}.json'

  # store locales for 1 day in localStorage
  useLocalStorage: true
  localStorageExpirationTime: 60 * 60 * 24 * 1000
})

Now you can use it everywhere in your asset pipeline - see i18next dokumentation for details.

Advanced Setup: precompiled assets

You might want to serve a static version of your assets to enable users to access your localization without incurring additional network requests.

First, load your latest locales into the asset pipeline:

# inside your application.coffee
#= require i18next.min
#= require i18n/translations

Next, instruct i18next to store the bundled locales locally

for bundledLocale of bundledLocales
  storedLocale = window.localStorage.getItem("res_#{bundledLocale}")?
  unless storedLocale?
    object = {}
    object[bundledLocale] = bundledLocales[bundledLocale]
    i18n.sync._storeLocal object

Lastly, initialize i18next like described above

This way your locales are instantly accessible. The next time the i18next updates all locales (your cached locales need to be older than localStorageExpirationTime ms) the locales are updated and voilĂ . Your user sees new content.

Advanced Setup: HandlebarsAsset integration

If you are using @leshill awesome handlebars_assets you might want to use a handlebars helper function to use it inside your views. This will get you started:

Handlebars.registerHelper 't', ->
  args = [].slice.call(arguments)
  result = i18n.t.apply(i18n,args)
  return new Handlebars.SafeString(result)

# inside your views

{{t "app.hello", name: "Max Mustermann"}} # => Hello %{name} -> Hello Max Mustermann