【问题标题】:Rails I18n: setting initial locale from HTTP_ACCEPT_LANGUAGE [duplicate]Rails I18n:从 HTTP_ACCEPT_LANGUAGE 设置初始语言环境 [重复]
【发布时间】:2012-11-15 05:22:16
【问题描述】:

感谢大家的帮助。

我在做什么: 我正在设计一个必须支持多种语言的公司网站

我做了什么: 具有多个静态页面的 Rails 应用程序。我使用 Ryan Bates 示例在 Rails 中使用 I18n 功能,特别是使用路由来设置语言环境:

MyApp::Application.routes.draw do

  scope ":locale", locale: /#{I18n.available_locales.join("|")}/ do
    root to: 'static_pages#home'

    match '/about', to: 'static_pages#about'
    match '/contact', to: 'static_pages#contact'
  end

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

我的 ApplicationController 如下所示:

class ApplicationController < ActionController::Base
  protect_from_forgery
  before_filter :set_locale

  private
    def set_locale      
        I18n.locale = params[:locale] || I18n.default_locale
    end    

    def default_url_options(options = {})
        {locale: I18n.locale}
    end       
end

我在服务器启动时的日志显示如下:

Started GET "/en" for 127.0.0.1 at 2012-11-14 22:41:01 +0400
Processing by StaticPagesController#home as HTML
  Parameters: {"locale"=>"en"}
  Rendered static_pages/home.en.html.erb within layouts/application (1.0ms)
Compiled custom.css  (5905ms)  (pid 9864)
Compiled application.css  (15ms)  (pid 9864)
  Rendered layouts/_shim.html.erb (0.0ms)
  Rendered layouts/_header.html.erb (12.0ms)
  Rendered layouts/_footer.html.erb (2.0ms)
Completed 200 OK in 6741ms (Views: 6740.4ms | ActiveRecord: 0.0ms)

我想做什么: 我希望当用户未在 url 中指定语言环境(例如,仅键入 www.example.com)时,rails 从request.env['HTTP_ACCEPT_LANGUAGE'].scan(/^[a-z]{2}/).first 获取接受的语言环境 并将访问者重定向到他的首选语言。在这一点上,我无法弄清楚我的 I18n.locale 首先是在哪里设置的。

【问题讨论】:

  • 这个问题有没有答案。我已经到了一半 - 但是,在我到达我的应用程序控制器中的 set_locale 之前设置了语言环境....

标签: ruby-on-rails internationalization routes http-accept-language


【解决方案1】:

这很神奇HTTP_ACCEPT_LANGUAGE

另一个要考虑的Locale Setter

后一种允许您检查用户偏好、http_accept_lang 代码等。

【讨论】:

    【解决方案2】:

    我正在处理与您完全相同的案例!也许你应该try this

    也可以参考my question 那里有有用的答案。

    一旦我得到这个工作,我会发布一个答案

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-05
      • 1970-01-01
      • 2012-01-18
      • 2012-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多