在Rails中动态添加活动类到bootstrap li [英] Dynamically add active class to bootstrap li in Rails

查看:72
本文介绍了在Rails中动态添加活动类到bootstrap li的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

引导导航栏中的

.您可以通过添加类active来获得单击按钮的效果.自然,我想在我的页面上使用它.例如,如果我在关于我们"页面上,则要单击关于我们"按钮.

解决此问题的最佳方法是什么?我要转到每个页面,在底部有一个jQuery函数,将类active添加到其中.有更好的方法吗?

解决方案

阅读有关current_page?的信息

示例引导导航栏模板

<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的详细信息,请此处

in the bootstrap navigation bar. You can get the effect of a button being clicked by adding the class active . Naturally, I want to use this on my pages. For example if I'm on the about us page I want the about us button clicked.

What is the best way to go about this? I was going to go to each page and at the bottom have a jQuery function add the class active to it. Is there a better way?

解决方案

Read about current_page? here

You can add a method for handle logic with current_page?, example a method :

module ApplicationHelper

 def active_class(link_path)
  current_page?(link_path) ? "active" : ""
 end

end

example bootstrap navbar template

<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>

So, on view looks like

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


Or you can use request.fullpath to get current full of path if a current path have a parameter

example

<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>

and on your application_helper.rb

def active_class(link_path)
  request.fullpath == link_path ? "active" : "" 
end

read about request.fullpath here

这篇关于在Rails中动态添加活动类到bootstrap li的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆