Rob Hughes
Rob Hughes

Reputation: 906

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

Upvotes: 1

Views: 1030

Answers (2)

Flautarian
Flautarian

Reputation: 51

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.

Upvotes: 0

Abid Iqbal
Abid Iqbal

Reputation: 773

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

Upvotes: 1

Related Questions