我在application.rb
中设置了locale
的基本选项:
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.com
和 www.mysite.com/en 或 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
最佳答案
如果用户在接受语言 header 中没有完善,即使您将其他非本地化路由重定向到完善,也最好将根路径重定向到英语。
# 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
在 Controller 中:
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
关于ruby-on-rails - Rails - 使用区域设置重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42863461/