Rails - 使用语言环境重定向

时间:2017-03-17 17:12:10

标签: ruby-on-rails redirect rails-i18n

我在locale中设置了application.rb的基本选项:

config.i18n.available_locales = [:pl, :en]
config.i18n.default_locale = :pl

并确定了路线:

Rails.application.routes.draw do
    get '/:locale', to: 'home#index'
    root            to: 'home#index'

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

这样,我可以在www.mysite.comwww.mysite.com/en or pl下访问我的根网站,以及在网址中包含区域设置时我的设置网站。

现在让我们说用户键入www.mysite.com/settings。我希望我的应用知道网址中没有区域设置,因此请抓住default_locale,设置它,然后重定向到www.mysite.com/pl/settings

我怎么能这样做?

PS我也将这些添加到我的ApplicationController

before_action :set_locale

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

    def default_url_options
      { locale: I18n.locale }
    end

2 个答案:

答案 0 :(得分:1)

如果用户在接受语言标题中没有优化,即使您将其他非本地化路由重定向到抛光,也最好重定向到根路径

 # Usefull to parse accept-language header but also for browser detection
 gem 'browser'

在routes.rb中:

Rails.application.routes.draw do
  scope ':locale', locale: /#{I18n.available_locales.join('|')}/ do
    # Your routes...

    # Home
    root 'pages#index'
  end

  root 'pages#detect_locale'

  # Catch all requests without a available locale and redirect to the PL default...
  # The constraint is made to not redirect a 404 of an existing locale on itself
  get '*path', to: redirect("/#{I18n.default_locale}/%{path}"), 
               constraints: { path: %r{(?!(#{I18n.available_locales.join('|')})\/).*} }
end

在控制器中:

class PagesController < ApplicationController
  def index; end

  # Detect localization preferences
  def detect_locale
    # You can parse yourself the accept-language header if you don't use the browser gem
    languages = browser.accept_language.map(&:code)

    # Select the first language available, fallback to english
    locale = languages.find { |l| I18n.available_locales.include?(l.to_sym) } || :en

    redirect_to root_path(locale: locale)
  end
end

答案 1 :(得分:-1)

Rails.application.routes.draw do
  scope ':locale', locale: /#{I18n.available_locales.join("|")}/ do
    root 'users/landing#index'
    get '*path', to: 'users/errors#not_found'
  end
  root to: redirect("/#{I18n.default_locale}", status: 302), as: :redirected_root
  get "/*path", to: redirect("/#{I18n.default_locale}/%{path}", status: 302)
end