简体   繁体   English

向控制器Ruby on Rails中的所有相关动作添加活动类

[英]Add active class to all relative actions inside controller Ruby on Rails

I am using the following helper to add is_active css class to active links in my navigation bar. 我正在使用以下helper程序将is_active CSS类添加到导航栏中的活动链接。

# application_helper.rb
def active_link_to(name = nil, options = nil, html_options = nil, &block)
  active_class = html_options[:active] || "is_active"
  html_options.delete(:active)
  html_options[:class] = "#{html_options[:class]} #{active_class}" if current_page?(options)
  link_to(name, options, html_options, &block)
end

This code works perfectly. 此代码完美地工作。 However, I want to keep is_active class on every page which related to the controller. 但是,我想在与控制器相关的每个页面上保留is_active类。 For example, here is my controller route: 例如,这是我的控制器路线:

# routes.rb
resources :catalogs, path: "s", only: [:index, :show] do
  resources :products, path: "", only: [:show]
end

and imagine that I have 100 different catalogs. 想象我有100个不同的目录。 I want to keep is_active on the index page, while the user switches show pages. 我想在索引页面上保持is_active ,而用户切换显示页面。

Link in my navigation bar: 我的导航栏中的链接:

= active_link_to "Products", catalog_path(1), class: "navbar_link"

Please note, that in the previous line I am navigation to the very first catalog, not to the index page. 请注意,在上一行中,我导航到第一个目录,而不是index页面。

Thank you for your help and time! 感谢您的帮助和时间!

You can try active_link_to gem, which does exactly what you want. 您可以尝试active_link_to gem,它完全可以满足您的需求。 It would be something like this (not tested) 可能是这样(未经测试)

active_link_to 'Products', catalog_path(1), active: [['catalogs'], ['index', 'show']], class_active: 'is_active'

暂无
暂无

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

相关问题 Rails模型是一个普通的ruby类,可用于在不同的控制器操作之间存储状态吗? 根本没有活动记录和无数据库 - Is a Rails Model a normal ruby class that can be used to store state between different controller actions? No active-record and no-database at all Rails:在控制器的所有动作中可见的属性 - Rails :An attribute seen inside all the actions of a controller 向轨道中的所有活动链接添加“活动”class? - Add an 'active' class to all active links in rails? 在Ruby on Rails中,如何将控制器中的所有动作映射到root? - In Ruby on Rails, how can I map all actions in a controller to root? 如何在Ruby on Rails中生成控制器动作数组? - How to generate an array of controller actions in Ruby on Rails? Ruby on Rails:一个控制器中动作的默认模板 - Ruby on Rails: Default template for actions in one controller 在Ruby on Rails中,如何将实例变量添加到类中(并在控制器中以JSON形式返回)? - In Ruby on Rails, how to add an instance variable to a class (and return as JSON in controller)? 是否可以将/ folder / sub_folder与ruby on rails中控制器的所有操作相匹配? - Is it possible to match /folder/sub_folder to all actions of a controller in ruby on rails? ruby on rails控制器类实例化ruby类吗? - ruby on rails Controller class instantiate a ruby class? Ruby on Rails中的Mailer控制器,活动记录查询 - Controller for Mailer in Ruby on Rails, Active Record query
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM