更改rails中当前页面导航链接的类

0xS*_*ina 2 ruby ruby-on-rails

对不起,我不知道标题应该是什么,所以有人请把它改成最适合我的问题.

基本上,我有一个这样的列表:

<li class="active"><%= link_to "Home", root_path %></li>
<li><%= link_to "About", about_path %></li>
<li><%= link_to "Contact", contact_path %></li>
Run Code Online (Sandbox Code Playgroud)

根据我所在的页面(Home,About,Contant),我希望相应的<li>标签具有class="active"属性.最好的方法是什么?

我有一个类变量@title设置为正在导航的任何页面.

rif*_*aff 11

使用current_page?(options)知道,如果控制器/动作/ PARAMS的网址相对应,并且基于与这样的一个助手切换类,如(未经测试):

 def nav_item(name, path)
   if current_page?(path)
     @title = name
   end
   content_tag('li', :class=>(current_page?(path) ? 'active' : nil) ){link_to(name,path)}
 end

<%= nav_item 'Home', root_path %>
<%= nav_item 'About', about_path %>
<%= nav_item 'Contact', contact_path %>
Run Code Online (Sandbox Code Playgroud)