如何在Rails中更改菜单项的类 [英] How to change a class of a menu item in Rails
问题描述
我有一个带菜单导航的布局。我正在使用我在网上找到的模板。每个菜单项都有一个HTML页面,每个相应页面的li项目类别被称为已选择。它看起来像这样:
I have a layout with a menu navigation. I'm using a template I found online. There is an HTML page for each menu item and the li item class is called "selected" for each corresponding page. It looks like this:
<nav>
<ul class="sf-menu" id="nav">
<li class="selected"><%= link_to "home", root_path %></li>
<li><%= link_to "about me", about_path %></li>
<li><%= link_to "my portfolio" %>
<ul style="z-index: 2;">
<li style="z-index: 2;"><%= link_to "portfolio one", portfolio_one_path %></li>
<li style="z-index: 2;"><%= link_to "portfolio two", portfolio_two_path %></li>
<li style="z-index: 2;"><%= link_to "portfolio three", portfolio_three_path %></li>
</ul>
</li>
<li><%= link_to "blog", blog_path %></li>
<li><%= link_to "contact", contact_path %></li>
</ul>
</nav>
所以这是我的 application.html.erb
文件。我的问题是如何根据用户点击的链接以编程方式将每个li项的类更改为已选择?这可以用Ruby完成还是我需要使用JavaScript?
So this is in my application.html.erb
file. My question is how do I programmatically change each li item's class to "selected" depending on which link the user clicks on? Can this be done with Ruby or do I need to use JavaScript?
推荐答案
我想你想要 current_page?
辅助方法 - http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-current_page-3F
I think you want the current_page?
helper method - http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-current_page-3F
<li class="<%= "selected" if current_page?(root_path) %>"><%= link_to "home", root_path %></li>
...
这篇关于如何在Rails中更改菜单项的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!