0

当用户在某个子页面上时,我有以下代码表示一个活动选项卡,在这种情况下是用户索引视图。

  <li class="<%='active' if current_page?(users_path) %>">
    <%= link_to 'Users',      users_path %></li>

我希望这样当用户在任何显示、编辑或索引页面上时,选项卡都会显示为“活动”。

我试过这样的事情:

  <li class="<%='active' if current_page?(users_path || edit_user_path || user_path) %>">
    <%= link_to 'Users',      users_path %></li>

但只有 users_path 被识别。

在 current_page 方法中构建 OR 语句的正确方法是什么?

4

2 回答 2

0

这是我在以前的应用程序中使用的一些代码。

def nav_item(copy, link)                             
  content_tag :li, class: nav_class(link) do         
    link_to copy, link                             
  end                                                
end

def nav_class(page)
  case page
  when :users     then 'active' if request.path.match(/^\/users/)
  when :projects  then 'active' if request.path.match(/^\/projects/)       
  else                                               
    nil                                              
  end                                                
end    

如果路由匹配当前路径,上面的两个辅助方法将在li标记内呈现链接。class="active"

不在 UsersController 操作上:

<%= nav_item('Users', :users) %>  #=> <li><a href="/users">Users</a></li>

在 UsersController 动作上:

<%= nav_item('Users', :users) %>  #=> <li class="active"><a href="/users">Users</a></li>
于 2013-03-10T01:24:04.187 回答
0

那应该是

<li class="<%='active' if current_page?(users_path) || current_page?(edit_user_path) || current_page?(user_path) %>">

如果您对很多页面执行此操作,这将很难维护。您最好使用 gem 进行语义导航。

于 2013-03-10T01:03:15.530 回答