8

我想通过客户端浏览器区域设置request.env['HTTP_ACCEPT_LANGUAGE']和 URL 设置区域设置。

  1. 如果用户访问一个 URL(例如:myapp.com),它应该检查HTTP_ACCEPT_LANGUAGE并重定向到正确的 URL(例如:myapp.com/en - 如果browserlocale是 en)

  2. 如果用户随后通过语言菜单选择不同的语言,则应将 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 已经设置好了。

有没有人有解决方案?也许通过中间件解决它?

4

1 回答 1

8

我会在你的路线上改变一些东西。

第一的:

scope :path => ":locale" do
  ... 
end

第二:

我看到你在这里尝试做什么:

match '', to: redirect("/#{I18n.locale}")

不过,这似乎是多余的。

我会摆脱那条线,只修改 set_locale 方法,如下所示:

# set the language
def set_locale
  if params[:locale].blank?
    redirect_to "/#{extract_locale_from_accept_language_header}"
  else
    I18n.locale = params[:locale]
  end
end
于 2012-05-24T19:37:53.233 回答