将类添加到菜单中的活动li

时间:2022-06-05 03:48:32

Here's my haml code:

这是我的haml代码:

%li.active
  %a{ :href => "#" } Home
%li
  %a{ :href => "#" } About
%li
  %a{ :href => "#" } Sign up
%li
  %a{ :href => "#" } Log in

What would be the cleanest way of adding the .active attribute to the element which represents the current page? I've thought of passing a string to the template and looping through all the elements, building the menu from a hash, but it seems like there has to be a cleaner way.

将.active属性添加到代表当前页面的元素的最简洁方法是什么?我想过将一个字符串传递给模板并循环遍历所有元素,从哈希构建菜单,但似乎必须有一个更清洁的方式。

Is there a 'correct' way of doing this? I have to assume it's a very common operation.

这样做有“正确”的方法吗?我必须假设这是一个非常常见的操作。

Thanks

1 个解决方案

#1


3  

If you don't have too many navigation items, you could do something like this:

如果您没有太多导航项,您可以执行以下操作:

%li{ :class => @selected == :home ? "active" : nil }

#1


3  

If you don't have too many navigation items, you could do something like this:

如果您没有太多导航项,您可以执行以下操作:

%li{ :class => @selected == :home ? "active" : nil }