开发者

using Rails 3 root_path and root_to with locale url-paths

开发者 https://www.devze.com 2023-03-09 02:39 出处:网络
I have a simple route, and a simple main menu: routes.rb scope \"(:locale)\", :locale => /en|nl/ do resources :posts, :only => [:show, :index]

I have a simple route, and a simple main menu:

routes.rb

scope "(:locale)", :locale => /en|nl/ do
  resources :posts, :only => [:show, :index]
end
root :to => "posts#index"

menu

%ul#nav-language
  %li.alpha
    = menu_link_to(t('app.english'), root_path) 
  %li.omega
    = menu_link_to(t('app.nederlands'), "/nl/posts")
%ul#nav-section
  %li
    = menu_link_to(t('app.blog'), {:controller => "posts", :action => "index")
  -#more %li's.

menu_link_to is a simple wrapper around link_to, with an addition to set an "active" class when the current menu is selected:

  def menu_link_to(title, options = {}, html_options = {})
    if current_page?(options)
      html_options[:class] ||= []
      html_options[:class] << "active"
    end

    link_to(title, options, html_options)
  end

As you can see, I have two menu-items pointing the the root. In a more visual way, my menu looks like:

开发者_如何转开发
  • EN -> /
    • Blog -> /
    • About etc.
  • NL -> /nl/posts
    • Blog -> /nl/posts. In menu this is the same entry as the English, only with a different locale prefix.

I don't really mind if the EN and EN»Blog links to /en/posts, if that simplifies stuff.

But right now, current_path() will return FALSE when visiting root path. It also behaves weird, in the sense that rails will try to set locale as a ?name=value param: /?locale=en.

I think I am missing something crucial wrt root_path or routing. Any ideas?

EDIT: clarified the "Blog" item.


Have you tried to add matching in your routes.rb file? Right before root to:

match '/:locale' => 'dashboard#index'

It is mentioned in Rails Internationalization (I18n) API

Or you can just put root also into scope like this:

scope "(:locale)", :locale => /en|nl/ do
  resources :posts, :only => [:show, :index]
  root :to => "posts#index"
end

Then if you don't specify locale, default locale will be used.

0

精彩评论

暂无评论...
验证码 换一张
取 消