How to correctly implement I18n in Blacklight for field labels?

120 Views Asked by At

The docs are sketchy on how to do it properly. I tried this:

class ApplicationController < ActionController::Base
  # ...
  before_action :set_locale
  def set_locale
    session[:locale] = I18n.locale = params.delete(:locale) || session[:locale] || I18n.default_locale
  end
end

And this suffices for a lot of things; however, my fields are configured like this (following the Blacklight guide):

class CatalogController < ApplicationController
  include Blacklight::Catalog

  configure_blacklight do |config|
    # ...
    config.add_facet_field 'date', label: 'Date', single: false
    # ...
  end
end

This configuration happens before the request is processed, so if I try to use I18n.t('Date') for label, it will not respond to changes in locale, and will always serve the labels corresponding to the default locale.

What is the "correct" way to do this?

EDIT: Found the solution for the individual fields. Still searching for the "proper" solution for the search fields (config.add_search_field). It seems those are just displaying their label if present, and #labelize-d key if not. As a quick stop-gap measure, I made this class:

class Localized
  def initialize(key)
    @key = key
  end

  def to_s
    I18n.t(key)
  end
end

and configured the search field with

... label: Localized.new('blacklight.search.general.all_fields')
1

There are 1 best solutions below

0
Amadan On

Thanks to Surya, I saw where to look. The helper methods are already being invoked by the Blacklight's default templates, as long as one uses the correct keys. So, to localise the date field label in English, one needs the key named en.blacklight.search.fields.date.