Search code examples
ruby-on-railsslim-lang

Dynamically add active class to li within Rails using Slim


I'm trying to add an active class to list items while using slim. Right now I have the following code:

      li.nav-active = link_to 'One', '/one'
      li.nav-active = link_to '2', '/2'
      li = link_to 'A', '/a'
      li = link_to 'B', '/c'
      li = link_to 'D', '/d'

Then for my helper I'm using:

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

This doesn't seem to actual work. The first two list items automatically get the CSS applied to nav-active regardless of being active.

So then I switched to the following:

      li#{active_class('/one')} = link_to 'One', '/one'
      li.nav-active = link_to '2', '/2'
      li = link_to 'A', '/a'
      li = link_to 'B', '/c'
      li = link_to 'D', '/d'

With the following helper:

def active_class(link_path)
  current_page?(link_path) ? "nav-active" : ""
end

The issue here is that I get Slim::Parser::SyntaxError. Expected attribute.

So is there a good way to apply active class for the current page while using Slim?


Solution

  • Just in case someone needs to know this for the future here's the answer.

    li class="#{active_class('/url')}" = link_to 'Name', '/url'