简体   繁体   English

活动项目菜单RoR

[英]Active item menu RoR

How I can get active item menu? 如何获得活动项目菜单? Menu generate in cycle 菜单循环生成

<ul id="menu">  
  <% for page in Page.roots %>  
    <li><%= link_to h(page.name), page %></li>    
  <% end %>
  </ul> 

I want use other css property for this item. 我想为此项目使用其他CSS属性。 Any ideas? 有任何想法吗? Preferably js, jquery... 最好是js,jquery ...

$("#menu a[href$='+location.pathname+']").addClass('current');

The selector #menu a will find all links in your menu. 选择器#menu a将在菜单中找到所有链接。 [href$='+location.pathname+'] this will find the link which ends with ( $= ) the same path as the current page, and than adds with .addClass('current') the css class current [href$='+location.pathname+']这将找到以( $= )结尾的链接与当前页面相同的路径,然后以.addClass('current')添加CSS类current

There's link_to_unless_current which wraps the link into an a tag unless the link is the current page (shows just the text without a tag). link_to_unless_current包装了链接到a标签,除非该链接是当前页面(不显示只是文本a标签)。 With some CSS tricks you can make that into different appearance. 使用一些CSS技巧,您可以将其变成不同的外观。 I usually use this approach: 我通常使用这种方法:

<ul id="menu"><%= Page.roots.map do |page|
  content_tag :li, link_to_unless_current(h(page.name), page)
end %></ul>

and the following CSS: 和以下CSS:

ul#menu li { ...current/selected appearance... }
ul#menu li a { ...linked/normal appearance... }

I tend to generate my own helper for this kind of thing: 我倾向于为这种事情生成自己的助手:

#navigation_helper.rb
def nav_item(name, link, hilight = false)
  content_tag :li, link_to(name, link), :class => ("selected" if hilight)
end

Then in your views just pass a relevant boolean to the helper: 然后,在您的视图中,只需将一个布尔值传递给助手即可:

<ul id="menu">
  <%= nav_item "Foo admin", admin_path, (params[:controller] == "admin") %>
  <%= nav_item "Bar page", pages_path(@page), (params[:controller] == "pages" && params[:action] == "show" && params[:id] == @page.id) %>
  <%= nav_item "Baz example", example_path, any_old_helper? %>
</ul>

You'd need to think of a way of implementing this technique for your dynamically generated collection of pages, but where there's a will there's a way. 您需要为动态生成的页面集合考虑一种实现此技术的方法,但是只要有意愿,就有一种方法。 :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM