1

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

4
  • Did you include //= require moment/es.js in application.js file?
    – Abid Iqbal
    Aug 10, 2016 at 10:59
  • Yes, I have //= require moment //= require moment/es.js in my application.js file
    – Rob Hughes
    Aug 10, 2016 at 11:00
  • 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
    Aug 10, 2016 at 11:06
  • 1
    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
    Aug 10, 2016 at 11:11

2 Answers 2

1

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

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.