【问题标题】:Add active class to all relative actions inside controller Ruby on Rails将活动类添加到控制器 Ruby on Rails 内的所有相关操作
【发布时间】:2018-11-29 10:00:00
【问题描述】:

我正在使用以下helperis_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

此代码完美运行。但是,我想在与控制器相关的每个页面上保留 is_active 类。例如,这是我的控制器路由:

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

并想象我有 100 个不同的目录。我想在索引页面上保留is_active,而用户切换显示页面。

我的导航栏中的链接:

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

请注意,在上一行中,我导航到第一个目录,而不是 index 页面。

感谢您的帮助和时间!

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-5 haml


    【解决方案1】:

    您可以尝试active_link_to gem,它完全符合您的要求。应该是这样的(未测试)

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

    【讨论】:

    • 非常感谢,工作:) 不知道这个gem
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-21
    • 1970-01-01
    相关资源
    最近更新 更多