【问题标题】:rails routes with scope locale具有范围区域设置的 rails 路线
【发布时间】:2013-01-31 11:57:21
【问题描述】:

我在我的应用程序中添加了另一种语言。因此,我对静态页面使用以下路由:

scope "(:locale)", locale: /en|br/ do
  get "static_pages/about"
  match '/about', to: 'static_pages#about'
  ...
end

它工作正常,结果:

http://localhost:3000/en/about

但是,每次我在语言之间切换时,它都会返回完整路径而不是匹配:

http://localhost:3000/en/static_pages/about

我切换语言的方式:

#links
<%= link_to (image_tag '/england.png'), url_for( locale: 'en' ) %>
<%= link_to (image_tag '/brazil.png'), url_for( locale: 'br' ) %>  

#application controller
before_filter :set_locale
def set_locale
  I18n.locale = params[:locale]
end

def default_url_options(options={})
  { locale: I18n.locale }
end

这是一个问题,因为我在我的 CSS 文件中使用当前路径,所以每次我切换语言时都会弄乱布局:

<%= link_to (t 'nav.about'), about_path, class: current_p(about_path) %> 

#helper
def current_p(path)
   "current" if current_page?(path)
end

我正在尝试找到一种在切换语言时返回match 路由的方法。有什么想法吗?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 routing locale


    【解决方案1】:

    我已经解决了结合matchget 的问题。
    所以,而不是:

    scope "(:locale)", locale: /en|br/ do
      get "static_pages/about"
      match '/about', to: 'static_pages#about'
      ...
    end
    

    我现在有:

    scope "(:locale)", locale: /en|br/ do
      match '/about', to: 'static_pages#about', via: 'get'
      ...
    end
    

    编辑 - 感谢sevenseacat,这是一个更简单、更短的解决方案:

    scope "(:locale)", locale: /en|br/ do
      get '/about' => 'static_pages#about'
      ...
    end
    

    【讨论】:

    • 使用get '/about' =&gt; 'static_pages#help'会更短(也更容易)。
    • 使用(:locale)/:locale有什么区别?
    • @ArnoldRoa,它使 :locale 可选“如果您不想在路由中强制使用语言环境,您可以使用可选的路径范围(由括号表示)”guides.rubyonrails.org/i18n.html
    猜你喜欢
    • 2016-08-27
    • 2012-01-03
    • 2013-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-17
    • 1970-01-01
    相关资源
    最近更新 更多