Reputation: 319
I am trying to make an IF statement depending on the language that triggers certain JS code.
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 %>
Apparently it works. However, when I change the language on my app, the behavior of this code does not change. It still triggers the code of the previous locale.
Does not matter how many times I change the language. It will only trigger the code for the locale I opened the first window with.
Why is that? What am I doing wrong?
--------------------UPDATE------------
As suggested by @tigrish I iinstalled i18n-js gem.
I added this haml to my application.html.haml
:javascript
I18n.defaultLocale = " I18n.default_locale ";
I18n.locale = " I18n.locale ";
And tried to get the locale in JS the code provided in the gem docs.
var fo = I18n.currentLocale();
alert(fo);
However, it does not work.
Any idea why?
Upvotes: 2
Views: 2881
Reputation: 121
I had a similar problem and @tigrish solution helped me to solve it.
@SergioNekora, please try those steps:
gem 'i18n-js'
to your Gemfile).Add to application.html.erb file (for haml file you should use some other syntax):
<script type="text/javascript">
I18n.locale = "<%= I18n.locale %>";
</script>`
Add to temp.js.erb/temp.js file //= require i18n
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;
}
Upvotes: 1
Reputation: 2518
I think @marcgg is probably right with regards to cacheing.
You might consider using https://github.com/fnando/i18n-js - even if you don't include any translations per se, your I18n.locale == 'foo'
calls will all be in JS and interpreted every time the function runs.
Upvotes: 1
Reputation: 66436
I'd say that since it's javascript code it might be cached. Try clearing cache and checking if the language changes. If it does, either deactivate the cache for this file or make it depend on the locale.
Upvotes: 0