1
votes

I have moment using the momentjs-rails gem, and I have added the Spanish locale in javascripts/moment/es.js. I use the I18n gem and I'm unable to switch the moment language when I switch the app's global language.

Adding , moment.locale('es'); makes it show in Spanish, and adding; moment.locale('en'); makes it show in English but it won't change with I18n.

I have tried in application.js.erb

<% if I18n.locale == :es %>
     moment.locale('es');
<% end %>
<% if I18n.locale == :en %>
     moment.locale('en');
<% end %>

but moment's language stays as the 'top' option, in this case 'es'.

So with;

<% if I18n.locale == :en %>
     moment.locale('en');
<% end %>
<% if I18n.locale == :es %>
     moment.locale('es');
<% end %>

the top option is 'en' so it displays in English.

How can I make moment.js language change when I change the language in I18n????

2
Did you include //= require moment/es.js in application.js file?Abid Iqbal
Yes, I have //= require moment //= require moment/es.js in my application.js fileRob Hughes
put this code in application.html ,switch the language and refresh page and check whether it works for you instead of putting it to application.js.erb. <script type="text/javascript"> <% if I18n.locale == :en %> moment.locale('en'); <% end %> <% if I18n.locale == :es %> moment.locale('es'); <% end %> </script>Abid Iqbal
Well I tried that before but I must have made a mistake because your code is working for me. Put it as an answer and I'll accept it.Rob Hughes

2 Answers

1
votes

Put this code in application.html,switch the language and refresh page. Check whether it works for you instead of putting it to application.js.erb.

 <script type="text/javascript">
   <% if I18n.locale == :en %>
     moment.locale('en');
   <% end %> 
   <% if I18n.locale == :es %>
     moment.locale('es');
   <% end %> 
</script>

Thanks

0
votes

To do this you will need to put down the actual i18n language of the web to js, can be done like this:

in main layout or application.js

var i18n_locale = "<%= I18n.locale %>"

and when you will initialize momentjs:

moment.locale('en');

I hope that it helps.