Rails 4 - 在 URL 中明确声明 none 时使用默认语言环境
Rails 4 - Use default locale when none is explicetely declared in the URL
这是我在 Rails 4
中的路由文件
root 'static_pages#root'
get '/:locale' => 'static_pages#root', as: 'locale_root'
scope "(:locale)", locale: /en|de/ do
# Everything else.,,
end
这会创建正确的 url,例如 http://localhost:3000/en/books
或 http://localhost:3000/de/books
。
但现在我希望如果没有指定语言环境,例如 http://localhost:3000/books
它仍会显示默认语言环境(英语)。
目前我得到的只是一个简单的 "books" is not a valid locale
.
我该怎么做?
其他文件
应用程序控制器
class ApplicationController < ActionController::Base
before_action :set_locale
protected
def set_locale
I18n.locale = params[:locale] || I18n.default_locale
end
def default_url_options(options = {})
{ locale: I18n.locale }.merge options
end
config/application.rb
config.i18n.default_locale = :en
config.i18n.fallbacks = [:en]
试试这个
root 'static_pages#root'
get '/books', to: redirect('/en/books')
get '/:locale' => 'static_pages#root', as: 'locale_root'
scope "(:locale)", locale: /en|de/ do
# Everything else.,,
end
你的路由文件看起来正确,试试这个 application_controller
class ApplicationController < ActionController::Base
before_filter :set_locale
def set_locale
I18n.locale = params[:locale] || I18n.default_locale
end
def default_url_options(options = {})
{ locale: I18n.locale == I18n.default_locale ? nil : I18n.locale }
end
end
注意 default_url_options 中的区别,当区域设置为默认区域时,它设置为 nil。
编辑: 正如 Dbugger 所说,root
必须在 routes.rb
中的 scope
内
scope "(:locale)", locale: /en|de/ do
root 'static_pages#root'
end
这是我在 Rails 4
中的路由文件root 'static_pages#root'
get '/:locale' => 'static_pages#root', as: 'locale_root'
scope "(:locale)", locale: /en|de/ do
# Everything else.,,
end
这会创建正确的 url,例如 http://localhost:3000/en/books
或 http://localhost:3000/de/books
。
但现在我希望如果没有指定语言环境,例如 http://localhost:3000/books
它仍会显示默认语言环境(英语)。
目前我得到的只是一个简单的 "books" is not a valid locale
.
我该怎么做?
其他文件
应用程序控制器
class ApplicationController < ActionController::Base
before_action :set_locale
protected
def set_locale
I18n.locale = params[:locale] || I18n.default_locale
end
def default_url_options(options = {})
{ locale: I18n.locale }.merge options
end
config/application.rb
config.i18n.default_locale = :en
config.i18n.fallbacks = [:en]
试试这个
root 'static_pages#root'
get '/books', to: redirect('/en/books')
get '/:locale' => 'static_pages#root', as: 'locale_root'
scope "(:locale)", locale: /en|de/ do
# Everything else.,,
end
你的路由文件看起来正确,试试这个 application_controller
class ApplicationController < ActionController::Base
before_filter :set_locale
def set_locale
I18n.locale = params[:locale] || I18n.default_locale
end
def default_url_options(options = {})
{ locale: I18n.locale == I18n.default_locale ? nil : I18n.locale }
end
end
注意 default_url_options 中的区别,当区域设置为默认区域时,它设置为 nil。
编辑: 正如 Dbugger 所说,root
必须在 routes.rb
scope
内
scope "(:locale)", locale: /en|de/ do
root 'static_pages#root'
end