具有可选范围“:locale"的 Rails 路由 [英] Rails routes with optional scope ":locale"
问题描述
我正在开发一个 Rails 3.1 应用程序,我想为该应用程序将支持的不同语言设置特定的路由.
I'm working on a Rails 3.1 app and I'd like to set specific routes for the different languages the app is going to support.
/es/countries
/de/countries
…
对于默认语言 ('en'),我不希望在 url 中显示区域设置.
For the default language ('en'), I don't want the locale to be displayed in the url.
/countries
这是我设置的路由定义.
Here is the route definition I've set.
scope "(:locale)", :locale => /es|de/ do
resources :countries
end
效果很好,直到我尝试使用带有en"作为语言环境的路径助手.
It works great, until I try to use a path helper with 'en' as the locale.
在控制台中:
app.countries_path(:locale => 'fr')
=> "/fr/countries"
app.countries_path(:locale => 'en')
=> "/countries?locale=en"
我不想要?locale=en".
I don't want the "?locale=en".
有没有办法告诉 rails 使用en"语言环境时,不应将语言环境参数添加到 url 中?
Is there a way to tell rails that with an 'en' locale, the locale param should not be added to the url?
谢谢
推荐答案
我终于想出了如何轻松做到这一点.您只需在应用控制器中设置 default_url_options 如下.
I finally figured out how to do it easily. You just have to set the default_url_options in the app controller as below.
def default_url_options(options={})
{ :locale => I18n.locale == I18n.default_locale ? nil : I18n.locale }
end
这样,您可以确定语言环境不会发送到路径助手.
This way, you are sure the locale isn't sent to the path helpers.
这篇关于具有可选范围“:locale"的 Rails 路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!