突出显示菜单中的选项卡
我有一个菜单,这是一个ul
Home | Calendar | Settings
我想突出显示(通过css类)菜单中的选定选项卡。
某些链接(主页和日历)也有子选择
Home | *Calendar* | Settings ------------------------- Add event | Edit event
当选择编辑事件时,仍应突出显示日历。
我怎样才能最好地使用rails和css来解决这个问题?
谢谢
最简单的方法是检查使用哪个控制器。 我编写了控制器名称,所以你当然会用正确的名字替换’home’,’calendar’和’settings’。
- ">Home
- ">Calendar
- ">Settings
在您的帮助文件中:
def is_active?(page_name) "active" if params[:action] == page_name end
在模板文件中:
link_to 'Home', '/', :class => is_active?("index") link_to 'About', '/about', :class => is_active?("about") link_to 'contact', '/contact', :class => is_active?("contact")
我发现了这个: http : //juliocapote.com/post/52081481/highlight-link-based-on-current-page-in-rails
我决定使用这个我非常喜欢的解决方案:
在帮手
def active_if(options) if params.merge(options) == params 'nav-active' end end
在视图中定义了路由的唯一性:
<%= link_to 'Home', root_path, class: active_if(action: 'home') %> <%= link_to 'Aricles', articles_path, class: active_if(controller: 'articles') %>
我有同样的问题,最终创建帮手。 基本上它取代了link_to url helper,所以它用li包装了链接,如果当前控制器与链接控制器匹配,则添加类“menu_selected”
使用样本
<%= menu_link_to "Home", home_path %>
def menu_link_to(*args, &block) url = args[1] mapping = ActionController::Routing::Routes.recognize_path(url) class_property = "menu_selected" if mapping[:controller] == controller.controller_path content_tag :li, :class => class_property do link_to *args, &block end end
def menu_link_to(*args, &block) url = args[1] mapping = ActionController::Routing::Routes.recognize_path(url) class_property = "menu_selected" if mapping[:controller] == controller.controller_path content_tag :li, :class => class_property do link_to *args, &block end end
更新@ ahmy对Rails 3.2的回答:
def menu_list_item(*args, &block) url = args[1] mapping = Rails.application.routes.recognize_path(url) li_class = 'active' if mapping[:controller] == controller.controller_path content_tag :li, :class => li_class do link_to *args, &block end end
即Rails.application.routes.recognize_path
而不是ActionController::Routing::Routes.recognize_path
。