Our great sponsors
-
rails-i18n
Repository for collecting Locale data for Ruby on Rails I18n as well as other interesting, Rails related I18n stuff
-
SurveyJS
Open-Source JSON Form Builder to Create Dynamic Forms Right in Your App. With SurveyJS form UI libraries, you can build and style forms in a fully-integrated drag & drop form builder, render them in your JS app, and store form submission data in any backend, inc. PHP, ASP.NET Core, and Node.js.
Everything else is set up like site/welcome, but here, we introduce pluralization for countable things. I18n is able to select the appropriate translation based on the variable passed to it. If you see that pluralization is not working well for your locale, it's a good idea to enhance your Rails app with the rails-i18n gem.
Finally, we are ready to add a Product model with the ability to add dynamic translation. First, we will use the mobility gem. Mobility is a gem for storing and retrieving translations as attributes on a class. It has several strategies for storing translations and works perfectly with both ActiveRecord and Sequel.
// app/javascript/src/helpers/price.js // Turbolinks are enabled by default in Rails, // we need to process our script on every page load // https://github.com/turbolinks/turbolinks#full-list-of-events document.addEventListener("turbolinks:ready", () => { // Get language from html tag const lang = document.documentElement.lang; // Find all span tags with data-localize="price" const pricesOnPage = document.querySelectorAll("[data-localize=\"price\"]"); if (pricesOnPage.length > 0) { // Iterate all price span tags [...pricesOnPage].forEach(priceOnPage => { // Modify text in span tag according to current language priceOnPage.textContent = priceOnPage.textContent.toLocaleString( lang, { style: "currency", currency: "USD" } ); }) } });
If you need more precise control over the display of dates and times, I recommend delegating such functionality to JavaScript by adding the date-fns library. Just create a helper and bypass data to this library like we will do with number rendering.
Related posts
- Supercharge Your TypeScript App: Mastering i18next for Type-Safe Translations
- What is the best way to handle a multi-language site?
- Advanced enterprise localisation process with Lingui, Locize, Github Actions, Docker, React
- How to internationalize a Remix application
- How to Internationalize Your App’s Product Notifications