在Rails中使用Slim动态为li添加active类的问题排查
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'
Step 2: Verify current_page? Path Matching (Optional but Recommended)
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

