Rob Hughes Rob Hughes - 3 months ago 55
jQuery Question

Ruby on rails - moment.js switch languages with I18n

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

Answer

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