【问题标题】:Assigning active class for bootstrap Nav-pills - Ruby on Rails为引导导航药片分配活动类 - Ruby on Rails
【发布时间】:2026-01-24 23:35:01
【问题描述】:

我的 Rails 应用中有一个博客部分,我想知道根据打开的页面分配 CSS 类 active 的好方法是什么。

这应该通过.erbifdo 语句来完成吗?它需要反映帖子所在的类别。

博客分类表:

create_table "blog_categories", force: :cascade do |t|
  t.string "name"
  t.integer "parent_id"
  t.datetime "created_at", null: false
  t.datetime "updated_at", null: false
end

帖子表列: t.integer "category_id" - 这是与猫的 .id 相关的存储。

我的类别用NULL 中的parent_id 表示,子类别是那些将parent_id 设置为主要类别的.id 的类别。

【问题讨论】:

标签: ruby-on-rails ruby twitter-bootstrap


【解决方案1】:

您可以通过在 application_helper.rb 中定义一个函数来做到这一点

def active_class(path)
 "active" if current_page?(path)
end

current_page? 方法将在用户与传入的路径参数位于相同的 url 时返回活动状态。查看其documentation

那么在视图中你可以这样使用它。

<li class="<%= active_class new_user_session_path %>">

【讨论】:

  • 这比直接包含代码如:&lt;%= 'active' if current_page?(root_path) %&gt;好吗?
  • 两者在逻辑上是相同的,但从某种意义上说,定义一个函数更好,它可以使您的代码可重用和干净。
【解决方案2】:

我更喜欢你使用这些帮助器,下面一个是用于单路径 例如:

<li class="<%= active_class(first_path) %>">

def active_class(link_path)
 current_page?(link_path) ? 'active' : ''
end

这是一个用于多个链接数组 例如

<li class="<%= active_class_multiple([first_path, second_path]) %>">

# pass array of paths to get current page active link
def active_class_multiple(array)
  array.include?(request.path) ? 'active' : ''
end

【讨论】: