Rails: Internationalization of Javascript Strings?

前端 未结 10 1437
你的背包
你的背包 2020-12-07 10:45

So, we have an existing Rails 2.3.5 app that does not support Internationalization at all. Now, I\'m well familiar with Rails I18n stuff, but we have a LOT of output strings

10条回答
  •  生来不讨喜
    2020-12-07 10:58

    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!

提交回复
热议问题