So, we have an existing Rails 2.3.5 app that does not support Internationalization at all. Now, I'm well familiar with Rails I18n stuff, but we have a LOT of output strings inside /javascripts/
. I'm not a huge fan of this approach, but unfortunately it is too late to fix it now.
How might we internationalize strings stored in JS files in a Rails app? Rails doesn't even serve the JS files...
I'm thinking I could always have the Rails app serve up the JS files, but that seems pretty gross. Are there plugins to do this?
The Ruby I18n (shorthand for internationalization) gem which is shipped with Ruby on Rails (starting from Rails 2.2) provides an easy-to-use and extensible framework for translating your application to a single custom language other than English or for providing multi-language support in your application.
Functions to internationalize your extension. You can use these APIs to get localized strings from locale files packaged with your extension, find out the browser's current language, and find out the value of its Accept-Language header. See the Internationalization page for a guide on using this API.
Internationalization (sometimes shortened to "I18N , meaning "I - eighteen letters -N") is the process of planning and implementing products and services so that they can easily be adapted to specific local languages and cultures, a process called localization .
Angular Internationalizationlink Internationalization, sometimes referenced as i18n, is the process of designing and preparing your project for use in different locales around the world. Localization is the process of building versions of your project for different locales.
Why not something simple like:
<script type="text/javascript"> window.I18n = <%= I18n.backend.send(:translations).to_json.html_safe %> </script>
Then in JS you can do things like:
I18n["en-US"]["alpha"]["bravo"];
I've wrapped mine in an application helper.
def current_translations @translations ||= I18n.backend.send(:translations) @translations[I18n.locale].with_indifferent_access end
Then my call in my application.html.erb looks like this:
<script type="text/javascript"> window.I18n = <%= current_translations.to_json.html_safe %> </script>
This allows you to avoid having to know the current locale in JavaScript.
I18n["alpha"]["bravo"];
Or
I18n.alpha.bravo;
Balibu is abandoned. Use i18n-js: https://github.com/fnando/i18n-js
Ryan's solution above is perfect, except the backend needs to be initialized if it hasn't been already.
I18n.backend.send(:init_translations) unless I18n.backend.initialized?
# now you can safely dump the translations to json
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With