Reputation: 8087
I have a multilingual rails application. On the base.html.erb I am setting the lang attribute like that :
<html lang="<%= I18n.locale %>" ng-app="myApp">
Is that a good way to do it or there is a better one ?
Upvotes: 9
Views: 2617
Reputation: 738
Using I18n.locale
, which gets the locale for the current request is right-on if you want to use its value in a template. If you want to set the locale based on some logic for each request, consider calling a set_locale
method in an around_action
in ApplicationController. This example looks for a persisted user-selected locale, then looks for a cookie value, then defaults to the app config value. This also allows you to use and set a locale (via the cookie) for public pages in your app.
around_action :set_locale
def set_locale(&action)
# nil until set either as user attribute or via the signin page
locale = cookies[:locale]
if current_user
# Check a logged-in user's locale attribute. Changing the attribute is
# done via AJAX then reload, so this works when changing the attribute
locale = current_user.try(:locale)
cookies[:locale] = locale
elsif params[:locale]
# Set the locale cookie via a public page
locale = params[:locale].to_sym
cookies[:locale] = locale
end
I18n.with_locale(locale || I18n.default_locale, &action)
end
Then in any controller or view/layout, just as you have it:
<%= I18n.locale %>
Upvotes: 0
Reputation: 5192
It might work okay; although you might prefer setting the current locale within your controllers for better flexibility
class ApplicationController < ActionController::Base
helper_method :current_locale
...
private
def current_locale
@current_locale ||= begin
# complex logic, switching locale based on
# user defined locale, subdomain, params, etc...
end
end
end
Then in your view :
<html lang="<%= current_locale %>" ng-app="myApp">
...
Upvotes: 1