First, make sure your zh-CN.yml
is encoded in UTF-8, it looks like it's encoded in US-ASCII.
I18n.js
You can use the i18n-js
gem to add Javascript internationalization to the Rails asset pipeline (see https://github.com/fnando/i18n-js).
The i18n-js
gem automatically converts the translations in the config/locales/
directory to javascript. After you add this gem, call I18n.t
directly in your javascript (without the <%=
and %>
). Translations are stored in javascript and can be viewed at http://localhost:3000/assets/i18n/translations.js
.
Note that the i18n-js may not completely load between requests, so you may still get TranslationMissing
errors from time to time, but these should go away when you compile your assets. If this happens during development, try reloading the page.
Use
- Add
gem 'i18n-js'
to yourGemfile
. - Run
bundle install
. Add a
zh-CN.yml
file toconfig/locals/
with:zh-CN: hello: 你好
In
application.js
, add the i18n libraries before//= require_tree .
and set your default locale (make sure you keep the blank line)://= require i18n //= require i18n/translations //= require_tree . I18n.defaultLocale = "zh-CN";
Once that's done, your
hello.js.coffee.erb
file should look like this:$ -> alert I18n.t('hello')
You should then get the proper internationalized alert when you visit the page.