我想通过客户端浏览器区域设置request.env['HTTP_ACCEPT_LANGUAGE']
和 URL 设置区域设置。
如果用户访问一个 URL(例如:myapp.com),它应该检查
HTTP_ACCEPT_LANGUAGE
并重定向到正确的 URL(例如:myapp.com/en - 如果browserlocale
是 en)如果用户随后通过语言菜单选择不同的语言,则应将 URL 更改为例如:myapp.com/de。
这是我到目前为止得到的:
class ApplicationController < ActionController::Base
protect_from_forgery
before_filter :set_locale
private
# set the language
def set_locale
if params[:locale].blank?
I18n.locale = extract_locale_from_accept_language_header
else
I18n.locale = params[:locale]
end
end
# pass in language as a default url parameter
def default_url_options(options = {})
{locale: I18n.locale}
end
# extract the language from the clients browser
def extract_locale_from_accept_language_header
browser_locale = request.env['HTTP_ACCEPT_LANGUAGE'].try(:scan, /^[a-z]{2}/).try(:first).try(:to_sym)
if I18n.available_locales.include? browser_locale
browser_locale
else
I18n.default_locale
end
end
end
在我的路线文件中,我得到:
Myapp::Application.routes.draw do
# set language path
scope ":locale", locale: /#{I18n.available_locales.join("|")}/ do
root :to => "mycontrollers#new"
...
end
match '*path', to: redirect("/#{I18n.locale}/%{path}"), constraints: lambda { |req| !req.path.starts_with? "/#{I18n.default_locale}/" }
match '', to: redirect("/#{I18n.locale}")
end
问题是路由文件首先被执行并且HTTP_ACCEPT_LANGUAGE
没有效果,因为当涉及到控制器时,url-param 已经设置好了。
有没有人有解决方案?也许通过中间件解决它?