Raj*_*ajG 10 ruby locale ruby-on-rails
如何在rails上的ruby上自动设置语言环境?例如,如果网页在西班牙打开,那么locale = es,同样如果它在英国,那么locale = en和类似的?
请帮帮我.
MrY*_*iji 25
你可以在你的实现中实现它ApplicationController:
class ApplicationController < ActionController::Base
before_filter :set_locale
def set_locale
I18n.locale = extract_locale_from_headers
end
private
def extract_locale_from_headers
request.env['HTTP_ACCEPT_LANGUAGE'].scan(/^[a-z]{2}/).first.presence || 'en'
end
end
Run Code Online (Sandbox Code Playgroud)
它将"检查"收到的请求,找到客户端浏览器的语言并将其设置为I18n语言环境.
请查看关于I18n 的RubyOnRails指南以获取进一步的说明.
你甚至可以"过滤器"的提取从,如果你的应用程序不支持此语言环境的头区域(强烈推荐!),并使用"默认语言环境"与ApplicationController.像这样的东西:
ALLOWED_LOCALES = %w( fr en es ).freeze
DEFAULT_LOCALE = 'en'.freeze
def extract_locale_from_headers
browser_locale = request.env['HTTP_ACCEPT_LANGUAGE'].scan(/^[a-z]{2}/).first
if ALLOWED_LOCALES.include?(browser_locale)
browser_locale
else
DEFAULT_LOCALE
end
end
Run Code Online (Sandbox Code Playgroud)
或修订版(2018年)
class ApplicationController < ActionController::Base
before_filter :set_locale
def set_locale
I18n.locale = extract_locale_from_headers
end
private
def extract_locale_from_headers
request.env['HTTP_ACCEPT_LANGUAGE'].scan(/^[a-z]{2}/).first.presence || 'en'
end
end
Run Code Online (Sandbox Code Playgroud)
尝试使用gem geocoder和i18n_data gem并有一个before_filter到一个方法
def checklocale
I18n.locale = I18nData.country_code(request.location.country)
end
Run Code Online (Sandbox Code Playgroud)