Another option that could be helpful:
Supposing that you have a model Language (slug) that contains all your available languages.
It handles the cases when a there's a missing translation (it's replaced by the default locale version)
assets/javascript/i18n.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;
};
views/layout/application.html.erb
...
<%= javascript_tag "var current_locale = '#{I18n.locale.to_s}';" %>
<%= javascript_tag "var default_locale = '#{I18n.default_locale}';" %>
...
In you 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 that it helps!