Another option that may be useful:
Suppose you have a Language (slug) model that contains all available languages. It handles cases where there is no translation (it is replaced by the standard version of the locale)
assets / javascript / i 18n.js.erb
<% @translator = I18n.backend @translator.load_translations translations = {} Language.all.each do |l| translations[l.slug] = @translator.send(:translations)[l.slug.to_sym] end @translations = translations %> window.I18n = <%= @translations.to_json.html_safe %> window.I18n.t = function(key){ if(window.I18n[current_locale]){ el = eval("I18n['"+current_locale+"']." + key); } if(window.I18n[default_locale] && typeof(el) == 'undefined'){ el = eval("I18n['"+default_locale+"']." + key); } if(typeof(el) == 'undefined'){ el = key; } return el; };
view / layout / application.html.erb
... <%= javascript_tag "var current_locale = '#{I18n.locale.to_s}';" %> <%= javascript_tag "var default_locale = '#{I18n.default_locale}';" %> ...
In your javascript code, you can translate like this:
// current_locale:fr , default_locale:en // existing translation (in french) I18n.t('message.hello_world'); // => Bonjour le monde // non-existing translation (in french) but existing in english I18n.t('message.hello_this_world'); // => Hello this world // non-existing translation (french & english) I18n.t('message.hello_this_new_world'); // => message.hello_this_new_world
Hope this helps!
melalj May 24 '14 at 12:40 a.m. 2014-05-24 00:40
source share