我正在尝试使用
使用参数
request.location
(geocoder gem),根据客户端的IP地址适当设置区域设置。
这是我得到的内容:
app/controllers/application_controller.rb
before_action :set_locale
private
def set_locale
# get location with geocoder
location = request.location
# set locale through URL
if params.has_key?(:locale)
I18n.locale = params[:locale] || I18n.default_locale
# set locale through user preference
elsif current_user && current_user.locale.present?
I18n.locale = current_user.try(:locale) || I18n.default_locale
# set locale through geocoder detection of location
elsif location.present? && location.country_code.present? && I18n.available_locales.include?(location.country_code)
if location.country_code.include? "-"
I18n.locale = location.country_code
else
I18n.locale = location.country_code.downcase
end
# set locale through HTTP detection of location
elsif (request.env["HTTP_ACCEPT_LANGUAGE"] || "en").scan(/^[a-z]{2}/).first.present? && I18n.available_locales.include?((request.env["HTTP_ACCEPT_LANGUAGE"] || "en").scan(/^[a-z]{2}/).first)
I18n.locale = (request.env["HTTP_ACCEPT_LANGUAGE"] || "en").scan(/^[a-z]{2}/).first
end
end
config/application.rb
# i18n Translations
## load the subfolders in the locales
config.i18n.load_path += Dir["#{Rails.root.to_s}/config/locales/**/**/**/**/**/*.{rb,yml}"]
## set default locale
config.i18n.default_locale = 'en'
## provide locale fallbacks
config.i18n.enforce_available_locales = false
config.i18n.fallbacks = {
'de-AT' => 'de', 'de-CH' => 'de', 'de-DE' => 'de',
'en-AU' => 'en', 'en-CA' => 'en', 'en-GB' => 'en', 'en-IE' => 'en', 'en-IN' => 'en', 'en-NZ' => 'en', 'en-US' => 'en', 'en-ZA' => 'en'
}
使用参数
params[:locale]
,一切都很好。但是如果没有参数,它总是默认为en
。我在这里做错了什么?
session[:locale] = params[:locale] if params[:locale] != session[:locale]
来更新会话数据,当设置了新的语言环境时,应用程序会在每个请求中回退到en
。Rails 在后台设置了这个参数吗? - heroxavsession
将在请求之间被记住,但您的params
可能包含或不包含locale
。要在每个页面上包含它,您需要在生成URL时从控制器传递它到视图中。最好的方法是将params[:locale]
视为任何现有设置的显式、一次性覆盖,否则始终依赖于session[:locale]
(如果已设置)。 - gwcodessession[:locale]
已经被设置时,我无法通过仅检查unless session[:locale]
来覆盖它。我需要使用类似于if params[:locale]
的东西来准备好。而且感觉 Rails 在后台自动设置了这个,因为即使在 URL 中没有设置参数,它也会运行那段代码。 - heroxav