2

我正在尝试根据触发某些 JS 代码的语言来制作 IF 语句。

temp.js.erb

<% if I18n.locale.to_s == 'es' %>
    someJScode;
<% elsif I18n.locale.to_s == 'en' %>
    someJScode;
<% elsif I18n.locale.to_s == 'eu' %>
    someJScode;
<% elsif I18n.locale.to_s == 'fr' %>
    someJScode;
<% end %>

显然它有效。但是,当我更改应用程序的语言时,此代码的行为不会改变。它仍然会触发先前语言环境的代码。

不管我改变多少次语言。它只会触发我打开第一个窗口的语言环境的代码。

这是为什么?我究竟做错了什么?

- - - - - - - - - - 更新 - - - - - -

正如@tigrish 所建议的,我安装了 i18n-js gem。

我将此haml添加到我的application.html.haml

:javascript
      I18n.defaultLocale = " I18n.default_locale ";
      I18n.locale = " I18n.locale ";

并试图在 JS 中获取 gem 文档中提供的代码的语言环境。

var fo = I18n.currentLocale();
alert(fo);

但是,它不起作用。

知道为什么吗?

4

3 回答 3

1

我认为@marcgg 在缓存方面可能是正确的。

您可以考虑使用https://github.com/fnando/i18n-js - 即使您本身不包含任何翻译,您的I18n.locale == 'foo'调用也将全部在 JS 中并在每次函数运行时进行解释。

于 2013-02-08T11:20:33.403 回答
1

I had a similar problem and @tigrish solution helped me to solve it.

@SergioNekora, please try those steps:

  1. Install i18n-js (by adding gem 'i18n-js' to your Gemfile).
  2. Add to application.html.erb file (for haml file you should use some other syntax):

    <script type="text/javascript">
        I18n.locale = "<%= I18n.locale %>";
    </script>`
    
  3. Add to temp.js.erb/temp.js file //= require i18n

  4. Now, you can use I18n.locale variable inside temp.js.erb/temp.js file (without using ruby). For example:

    if (I18n.locale) == 'es' {
         someJScode;
    } else if (I18n.locale == 'en') {
         someJScode;
    }
    
于 2014-01-18T21:35:32.353 回答
0

我会说,因为它是 javascript 代码,它可能会被缓存。尝试清除缓存并检查语言是否更改。如果是这样,请停用此文件的缓存或使其依赖于语言环境。

于 2013-02-08T10:50:32.767 回答