[Java] Pass i18n locale to JavaScript

1 minute read

stuck while creating multilingual app

Using jQuery and Ajax, when the parent category is selected, candidate child categories will be displayed in a pull-down. However, only the child category was translated only in the default Vietnamese language.

Example: Parent category => Question Child category => 1, Ngôn ngữ và văn hóa 2, Tập huấn kỹ t huật ③ 3, Ứng dụng và thủ tục

Cause

This was because the locale was not passed to the controller when retrieving the child category with Ajax.

category_pulldown.js


$("#parent").on("change", function () {
  // Get the ID from the selected parent category
  var id = document.getElementById("parent").value;
// omitted
$.ajax({
  type:'GET',
  data: {parent_id: id }, // put the ID in params[:parent_id] and send
  url:'/categories/pulldown', // Get the child categories with the received ID in the categories controller
  dataType:'json',
}).done(function (children) {/ // Display the acquired child categories...

Although it is a partial excerpt, the locale was obtained by the following method.

application_controller.rb


before_action :set_locale

  private

  def set_locale
    I18n.locale = locale
  end

  def locale
    @locale ||= params[:locale] ||= I18n.default_locale
  end

  def default_url_options(options = {})
    options.merge(locale: locale)
  end

Pass the current locale to Java Script

First, use the input tag to hold the current locale. If you write type="hidden" as shown below, it will not be displayed on the screen from the user’s perspective.

hoge.html.erb


<input type="hidden" class="current_locale" value="<%= I18n.locale %>">

Then add locale: $('.current_locale').val() The translation languages for the parent and child categories have been unified.

category_pulldown.js


$("#parent").on("change", function () {
  // Get the ID from the selected parent category
  var id = document.getElementById("parent").value;
// omitted
$.ajax({
  type:'GET',
  data: {parent_id: id, locale: $('.current_locale').val() }, // put the ID in params[:parent_id] and send
  url:'/categories/pulldown', // Get the child categories with the received ID in the categories controller
  dataType:'json',
}).done(function (children) {/ // Display the acquired child categories...

HTML is convenient because you can pass information from Ruby and JavaScript. smiley: