Below code is what I have in one of coffeescript files in rails application. I'm struggling to add i18n support for string values like "Select Account First" and "Select One". In regular javascript files I have been using something like I18n.t("shared.select_account_first") to get the internationalized value for a string using i18n-js gem.
jQuery ->
networks = $('#account_offering_network_id').html()
select_network_options = new Option("Select Account First", "", true, false)
filter_networks_by_account = (account) ->
if account is 'Select One'
$('#account_offering_network_id').html(select_network_options)
else
escaped_account = account.replace(/([ #;&,.+*~\':"!^$[\]()=>|\/@])/g, '\\$1')
options = $(networks).filter("optgroup[label='#{escaped_account}']")
$('#account_offering_network_id').html(options.html())
# Show proper network dropdown first time
filter_networks_by_account($('#account_offering_account_id :selected').text())
# Show proper network dropdown on account change
$('#account_offering_account_id').change -> filter_networks_by_account($('#account_offering_account_id :selected').text())
The goal of all this is to filter networks dropdown based on account selected. If no account is selected (the value of account dropdown shows 'Select One' or corresponding i18n value), network dropdown should say 'Select Account First' in selected locale.
I'm using i18s-js gem(https://github.com/fnando/i18n-js) to enable translations in javascript. Here are the changes I had to make in application to support the gem.
In application.js:
//= require i18n
//= require i18n/translations
Properties added in production.rb and development.rb:
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation can not be found)
config.i18n.fallbacks = true
config.i18n.available_locales = [:en, :ru]
In application.html.erb:
<%# For localization/i18n in javascript %>
<script type="text/javascript">
I18n.defaultLocale = "<%= I18n.default_locale %>";
I18n.locale = "<%= I18n.locale %>";
I18n.fallbacks = true;
</script>
Finally I had run "rake i18n:js:export", which will create a translations file (app/javascripts/i18n/translations.js) loaded with name-value pairs. Now, from any javascript I can access the translations using I18n.t(name).