Ala*_*man 25 ruby-on-rails twitter-bootstrap twitter-bootstrap-rails
在引导程序导航栏中.您可以通过添加类来获得单击按钮的效果active.当然,我想在我的网页上使用它.例如,如果我在关于我们的页面上,我想点击关于我们的按钮.
最好的方法是什么?我打算去每个页面,在底部有一个jQuery函数将类添加active到它.有没有更好的办法?
rai*_*_id 55
在这里阅读current_page?  
您可以使用current_page?示例方法为句柄逻辑添加方法:
module ApplicationHelper
 def active_class(link_path)
  current_page?(link_path) ? "active" : ""
 end
end
示例引导程序导航栏模板
<div class="navbar">
  <div class="navbar-inner">
    <a class="brand" href="#">Title</a>
    <ul class="nav">
      <li class="active"><a href="#">Home</a></li>
      <li><a href="#">Link</a></li>
      <li><a href="#">Link</a></li>
    </ul>
  </div>
</div>
所以,在视图上看起来像
HTML
<li class="<%= active_class(some_path) %>">
<%= link_to "text of link", some_path %>
</li>
HAML
%li{:class => active_class(some_path)}
  = link_to "text of link", some_path
或者request.fullpath,如果当前路径具有参数,则可以使用此方法获取当前的完整路径
例
<ul>
 <% Contry.all.each do |c| %>
  <li class="snavitem <%= active_class(contry_path(c)) %>">
    <%= link_to "show #{c.name}", contry_path(c) %>
  </li>
 <% end %>
</ul>
在你的 application_helper.rb
def active_class(link_path)
  request.fullpath == link_path ? "active" : "" 
end
在这里阅读request.fullpath
Waw*_*Loo 14
在我看来,更简洁的方法是link_to_in_li在application_helper.rb中编写一个方法:
def link_to_in_li(body, url, html_options = {})
  active = "active" if current_page?(url)
  content_tag :li, class: active do
    link_to body, url, html_options
  end
end
然后以这种方式使用它
<%= link_to_in_li "Home", root_path, id: "home_link" %>
我觉得里面的代码li有点难以阅读.
对于任何无法理解这一点的人,这里有一个示例,我的路径和文件名明确地布局.作为一个相当新的铁杆人,我无法搞清楚.感谢上面回答的其他人,因为它帮助我解决了问题!
我将Bootstrap导航栏放在我的application.html.erb文件中:
<div class="navbar-header">
  <a class="navbar-brand" href="/">Mapper</a>
  <ul class="nav navbar-nav">
    <li class="<%= is_active?('/') %>"><%= link_to "Home", '/' %></li>
    <li class="<%= is_active?('/main/map') %>"><%= link_to "Map", '/main/map' %></li>
    <li class="<%= is_active?('/main/about') %>"><%= link_to "About", '/main/about' %></li>
  </ul>
</div>
这包含在application_helper.rb文件中:
module ApplicationHelper
def is_active?(link_path)
 current_page?(link_path) ? "active" : ""
end
end
而已!现在,您的应用程序将动态地将"活动"类添加到当前正在查看的任何页面(即,它是导航栏中的相应列表项).这比向每个页面(视图)手动添加导航栏然后更新"活动"类要简单得多(并且更干).