4

感谢大家的帮助。

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

我做了什么: 一个带有几个静态页面的 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 首先是在哪里设置的。

4

2 回答 2

1

这很神奇HTTP_ACCEPT_LANGUAGE

另一个要考虑的Locale Setter

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

于 2014-04-12T22:54:31.290 回答
0

I am working on exactly the same case as yours! perhaps you should try this

Also refer to my question where there are useful answers.

Once I get this working I will post an answer

于 2012-11-15T11:27:34.590 回答