Rails: Internationalization of Javascript Strings?

前端 未结 10 1417
你的背包
你的背包 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!

    0 讨论(0)
  • 2020-12-07 11:03

    Ryan's solution above is perfect, except the backend needs to be initialized if it hasn't been already.

    I18n.backend.send(:init_translations) unless I18n.backend.initialized?
    # now you can safely dump the translations to json
    
    0 讨论(0)
  • 2020-12-07 11:11

    Balibu is abandoned. Use i18n-js: https://github.com/fnando/i18n-js

    0 讨论(0)
  • 2020-12-07 11:11

    I18n-js is working great for me and i'd recommend it. If you use his rewrite branch then the plugin will include a /assets/i18n/filtered.js file which outputs exactly what @ryan-montgomery answered, without having to do anything yourself manually.

    This way, you can use the same translations on the backend with Rails helpers t(:key) and using I18n.t('key') in Javascript on the frontend.

    0 讨论(0)
提交回复
热议问题