Ruby on rails 更改rails中当前页面导航链接的类
对不起,我不知道标题应该是什么,所以有人请把它改成最适合我的问题 基本上,我有这样一个列表:Ruby on rails 更改rails中当前页面导航链接的类,ruby-on-rails,ruby,Ruby On Rails,Ruby,对不起,我不知道标题应该是什么,所以有人请把它改成最适合我的问题 基本上,我有这样一个列表: <li class="active"><%= link_to "Home", root_path %></li> <li><%= link_to "About", about_path %></li> <li><%= link_to "Contact", contact_path %></li>
<li class="active"><%= link_to "Home", root_path %></li>
<li><%= link_to "About", about_path %></li>
<li><%= link_to "Contact", contact_path %></li>
根据我所在的页面(主页、关于、Contant),我希望相应的
标记具有class=“active”
属性。最好的方法是什么
我将一个类变量@title设置为正在导航的任何页面。使用帮助程序。您将需要稍微不同的css,但这是值得的。您不必担心@title
等问题,也不会得到指向当前页面的混乱链接。例如,使用:
<nav>
<% [["Home", :home], ["About", :about], ["Contact", :contact]].each do |name,url| %>
<li><%= link_to_unless_current(name, url) %></li>
<% end %>
</nav>
使用当前页面?(选项)
了解控制器/操作/参数是否与url相对应,并基于此切换类,例如与这样的帮助器(未测试):
def导航项目(名称、路径)
如果是当前页面?(路径)
@title=名称
结束
content_标记('li',:class=>(当前_页面?(路径)?'active':nil)){link_to(名称,路径)}
结束
在应用程序\u controller.rb
中有一个before过滤器来实例化当前控制器和操作
# application_controller.rb
before_filter :instantiate_controller_and_action_names
def instantiate_controller_and_action_names
@current_action = action_name
@current_controller = controller_name
end
如果链接的操作和控制器是当前的,则定义一个助手来生成带有css类集的链接
module ApplicationHelper
def section_link_to(name, url_options, html_options = {})
if action.eql?(@current_action) and controller.eql?(@current_controller)
link_to(name, url_options, html_options, :class => 'current')
else
link_to(name, url_options, html_options)
end
end
end
定义css以突出显示活动链接:
nav li.active { /* current */
font-weight: bold;
background: green;
}
希望这能有所帮助。一个问题:你现在在哪一页上用哪种方式删除?这是不可能的,因为他不仅希望看到当前页,而且希望看到突出显示的当前页@大卫布:你说得对,但我希望我的答案能更接近rails实现他真正目标的方式。(尽管可能不是这样)
module ApplicationHelper
def section_link_to(name, url_options, html_options = {})
if action.eql?(@current_action) and controller.eql?(@current_controller)
link_to(name, url_options, html_options, :class => 'current')
else
link_to(name, url_options, html_options)
end
end
end
nav li.active { /* current */
font-weight: bold;
background: green;
}