【发布时间】:2012-05-12 02:25:32
【问题描述】:
我想通过客户端 browserlocale 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 在涉及到控制器时已经设置好了。
有人对此有解决方案吗?也许通过中间件解决?
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-3 internationalization i18n-gem