Rails 动态地为菜单导航加上 active,大家是怎么处理的?

zernel · July 13, 2012 · Last by ewinds replied at June 27, 2013 · 9692 hits

rt

jquery css class

$('#menu').find('a').each(function(){
  if (this.href == document.location.href || document.location.href.search(this.href) >= 0) {
    $(this).addClass('active'); // this.className = 'active';
  }
});
pathname =  window.location.pathname.split('/')[1];
  if(pathname) {
    jQuery('.mainNav li.' + pathname).addClass('active');
  } else {
    jQuery('.mainNav li.home').addClass('active');
  }

current_page?(),判断当前的 uri

我一般用这两种做法

  • 若这组 url 遵循比较统一的规则,则写一个 Helper 方法,根据 url 或者 controller/action 名字返回是否 active 的 css class
  • 若 url 规则比较乱,则在各自的 action 代码中赋值某个变量,如@active_page_a='active' 然后在页面中写上 class="@active_page_a"

可以参考 RubyChina 的做法,Ruby 生成

<%= 'active' if params[:controller] == 'home' %>

一般采用 link_to_unless_current,如果实现不了再自己写 Helper.

有时用 #7 楼 的方法,如果是多栏的话,为了减少 if 语句,我会这样

<% current = { action_name => 'active' } %>
<%= link_to xxx, xxx, :class => current['home']  %>
<%= link_to yyy, yyy, :class => current['index']  %>
Unknow user #11 August 16, 2012

额,那如果好几个路由都一个菜单呢。。。 我一般是写一个 hash 常量来配置菜单的 active

#12 楼 @hooopo 原来还可以这样

gem 'goose'

还是用 js 简单

@hooopo 这个真心不错哦! 如果有 2 级菜单呢?

我是写一个数组,作为配置,每一项有个名字;然后再写个方法渲染导航,在每个页面,使用不同的名字来调用。不过不太 OOP。

有个 Gist: https://gist.github.com/4015104

判断 action_name,我目前的做法。。

@zhangyuan 差不多,不过我是用嵌套的 yml,可以做多级的菜单。

Rails 中的方式不太熟悉. 使用 body 标签的 id 做高亮,纯 css/html:

css 代码:css/app.css

#home ul.nav li a.home,
#contact ul.nav li a.contact,
#about ul.nav li a.about {
/*高亮代码*/
}

Home Page:

<link ref="stylesheet" href="css/app.css" />
<body id="home">
    <ul class='nav'>
         <li><a href="" class='home'> Home </a></li>
         <li><a href="" class='contact'> Contact </a></li>
         <li><a href="" class='about'> About </a></li>
    </ul>
</body>

Contact Page:

<link ref="stylesheet" href="css/app.css" />
<body id="contact">
    <ul class='nav'>
         <li><a href="" class='home'> Home </a></li>
         <li><a href="" class='contact'> Contact </a></li>
         <li><a href="" class='about'> About </a></li>
    </ul>
</body>

About Page:

<link ref="stylesheet" href="css/app.css" />
<body id="about">
    <ul class='nav'>
         <li><a href="" class='home'> Home </a></li>
         <li><a href="" class='contact'> Contact </a></li>
         <li><a href="" class='about'> About </a></li>
    </ul>
</body>

ruby-china 用的是 bootstrap-helper 的 render_list

You need to Sign in before reply, if you don't have an account, please Sign up first.