简体   繁体   中英

Rails: Internationalization of Javascript Strings?

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 inside /javascripts/ . I'm not a huge fan of this approach, but unfortunately it is too late to fix it now.

How might we internationalize strings stored in JS files in a Rails app? Rails doesn't even serve the JS files...

I'm thinking I could always have the Rails app serve up the JS files, but that seems pretty gross. Are there plugins to do this?

Why not something simple like:

<script type="text/javascript">
  window.I18n = <%= I18n.backend.send(:translations).to_json.html_safe %>
</script>

Then in JS you can do things like:

I18n["en-US"]["alpha"]["bravo"];

I've wrapped mine in an application helper.

def current_translations
  @translations ||= I18n.backend.send(:translations)
  @translations[I18n.locale].with_indifferent_access
end

Then my call in my application.html.erb looks like this:

<script type="text/javascript">
  window.I18n = <%= current_translations.to_json.html_safe %>
</script>

This allows you to avoid having to know the current locale in JavaScript.

I18n["alpha"]["bravo"];

Or

I18n.alpha.bravo;

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

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

For rails 3 applications you could do this:

Create a i18n.js.erb file and add it to your application.js. And add this piece of code into the file.

<%
@translator = I18n.backend
@translator.load_translations
@translations ||= @translator.send(:translations)[I18n.locale][:javascript]
%>

window.I18n = <%= @translations.to_json.html_safe %>

I also scope my translations to not have a huge javascript file. My scope is :javascript.

Hope it helps someone!

Why not simply this in your Javascript file:

var a_message = "<%= I18n.t 'my_key' %>"

For this to work, you must add .erb to your Javascript file's extension.

You might also need to add the following line at the top of your Javascript file if you aren't using ruby >= 2.0.

<%# encoding: utf-8 %>

See the last comment of the accepted answer in this thread for more info: Encoding issues in javascript files using rails asset pipeline

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!

Babilu是一个Rails插件,可以为您完成此任务。

Ryan solution is brillant. But to not include the entire file you should use: @translations[I18n.locale].with_indifferent_access["alpha"] instead of I18n.backend.send(:translations)["alpha"]

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.

对于像你所描述的那样的应用程序“根本不支持国际化”和“现在修复它已经太晚了”我写了一个非常快速的方法:jQuery插件Quick-i18n: https//github.com/katio/ Quick-i18n演示(以及如何使用它): http//johannpaul.net/Quick-i18n/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM