You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Rails中使用Slim动态为li添加active类的问题排查

Fixing the Persistent nav-active Class on Slim List Items

Let's break down why your helper method isn't working and fix it step by step:

The Root Cause

Your first two list items are hardcoded with the nav-active class directly in the Slim template (li.nav-active = ...). This means no matter what your helper method evaluates, those li elements will always have that class—your helper's logic is being ignored because you're not using it for those items!

Step 1: Replace Hardcoded li Tags with Your Helper

Instead of manually writing li elements for every navigation item, use the create_link helper you built for all of them. This way, the class assignment is controlled entirely by the helper's conditional logic.

Here's how your Slim template should look:

= create_link 'One', '/one'
= create_link '2', '/2'
= create_link 'A', '/a'
= create_link 'B', '/c'
= create_link 'D', '/d'

Sometimes current_page? can be finicky with raw string paths (e.g., trailing slashes, inconsistencies between raw paths and named routes). For more reliable matching, use Rails named routes instead of raw strings if you're working in a Rails app. For example:

# Updated helper (uses named routes)
def create_link(text, path)
  class_name = current_page?(path) ? 'nav-active' : ''
  content_tag(:li, class: class_name) do
    link_to text, path
  end
end

# Slim template using named routes
= create_link 'One', one_path
= create_link '2', two_path
= create_link 'A', a_path
# ... and so on

Step 3: Test the Behavior

After updating the template, navigate to each page—only the list item matching the current page should have the nav-active class now. The hardcoded classes are gone, so your helper's logic will fully control which item is marked active.

Bonus: Handling Default Active State

If you want a default item (like a homepage) to stay active when no other specific path matches, adjust the helper slightly:

def create_link(text, path)
  is_active = current_page?(path) || (path == root_path && current_page?(root_path))
  class_name = is_active ? 'nav-active' : ''
  content_tag(:li, class: class_name) do
    link_to text, path
  end
end

内容的提问来源于stack exchange,提问作者Jake

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:48:33