Rails:Javascript 字符串的国际化?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2701749/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:32:05  来源:igfitidea点击:

Rails: Internationalization of Javascript Strings?

javascriptruby-on-railsinternationalization

提问by Matt Rogish

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.

因此,我们现有的 Rails 2.3.5 应用程序根本不支持国际化。现在,我很熟悉 Rails I18n 的东西,但是我们在/javascripts/. 我不是这种方法的忠实粉丝,但不幸的是现在修复它为时已晚。

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

我们如何将存储在 Rails 应用程序中的 JS 文件中的字符串国际化?Rails 甚至不提供 JS 文件......

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?

我想我总是可以让 Rails 应用程序提供 JS 文件,但这看起来很糟糕。有插件可以做到这一点吗?

回答by Ryan Montgomery

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:

然后在 JS 中,您可以执行以下操作:

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:

然后我在 application.html.erb 中的调用如下所示:

<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.

这使您不必知道 JavaScript 中的当前语言环境。

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

Or

或者

I18n.alpha.bravo;

回答by Felipe Elias Philipp

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

巴厘布被遗弃。使用 i18n-js:https: //github.com/fnando/i18n-js

回答by life_like_weeds

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

Ryan 上面的解决方案是完美的,除了后端需要初始化,如果它还没有的话。

I18n.backend.send(:init_translations) unless I18n.backend.initialized?
# now you can safely dump the translations to json

回答by Vince V.

For rails 3 applications you could do this:

对于 rails 3 应用程序,您可以这样做:

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

创建一个 i18n.js.erb 文件并将其添加到您的 application.js。并将这段代码添加到文件中。

<%
@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.

我还将我的翻译范围限定为没有巨大的 javascript 文件。我的范围是:javascript。

Hope it helps someone!

希望它可以帮助某人!

回答by Vince V.

Why not simply this in your Javascript file:

为什么不简单地在您的 Javascript 文件中这样做:

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

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

为此,您必须将 .erb 添加到您的 Javascript 文件的扩展名。

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

如果您不使用 ruby​​ >= 2.0,您可能还需要在 Javascript 文件的顶部添加以下行。

<%# 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

有关更多信息,请参阅此线程中已接受答案的最后一条评论:Encoding issues in javascript files using rails asset pipeline

回答by sblom

Babiluis a Rails plugin that does this for you.

Babilu是一个为你做这件事的 Rails 插件。

回答by melalj

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)

假设您有一个包含所有可用语言的模型语言(slug)。它处理缺少翻译的情况(它被默认的语言环境版本替换)

assets/javascript/i18n.js.erb

资产/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

视图/布局/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:

在您的 javascript 代码中,您可以这样翻译:

// 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!

希望它有帮助!

回答by macler

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"]

Ryan 的解决方案非常出色。但要不包括整个文件,您应该使用:@translations[I18n.locale].with_indifferent_access["alpha"]而不是I18n.backend.send(:translations)["alpha"]

回答by robbie613

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

I18n-js对我来说很好用,我会推荐它。如果您使用他的重写分支,那么该插件将包含一个/assets/i18n/filtered.js文件,该文件准确输出@ryan-montgomery 的回答,而无需您自己手动执行任何操作。

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.

这样,您可以在后端使用 Rails 助手t(:key)I18n.t('key')在前端使用Javascript 中使用相同的翻译。

回答by Johann Echavarria

For applications like the one you described "that does not support Internationalization at all" and "is too late to fix it now" I wrote a very quick approach: the jQuery plugin Quick-i18n: https://github.com/katio/Quick-i18ndemo (and how to use it): http://johannpaul.net/Quick-i18n/

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