How to set bootstrap active class

I have a standard bootstrap navbar in a partials/_header.erb partial Bootstrap Navbar Gist

I’m confused about how I should set bootstrap’s class=“active” in the navigation for a relevant page. My thinking in psuedo-code is that I want

        <li <% if(middleman.obj.for.current.url = this.articles.url) print 'class="active"' %> ><a href="page1.html">Page 1</a></li>

What middleman properties do I want to check against each other ?
Is there a better approach?

1 Like

Look at the nav_link helper here: https://github.com/epochwolf/epochwolf.com/blob/master/config.rb#L139-L150

  def nav_link(name, url, options={})
    options = {
      class: "",
      active_if: url,
      page: current_page.url,
    }.update options
    active_url = options.delete(:active_if)
    active = Regexp === active_url ? current_page.url =~ active_url : current_page.url == active_url
    options[:class] += " active" if active

    link_to name, url, options
  end

And see my usage of it here: https://github.com/epochwolf/epochwolf.com/blob/master/source/layouts/_header.html.haml

#site-title-wrapper
  #site-title
    %h1=link_to "Epoch Wolf", "/"
    %nav#site-nav
      =nav_link "Home", '/'
      %span.dot="&sdot;"
      =nav_link "Blog", '/blog/', active_if: %r{^/blog/}
      %span.dot="&sdot;"
      =nav_link "Projects", '/projects/'
      %span.dot="&sdot;"
      =nav_link "Photos", '/photos/', active_if: %r{^/photos/}
      %span.dot="&sdot;"
      =nav_link "Writing", '/writing/', active_if: %r{^/writing/}

To answer my original question from my pseudo code the middleman object i was looking for was current_resource. At the time I didn’t implement @epochwolf’s suggestion because I didn’t understand Middleman enough. Here’s the dumb simple helper I found:

def nav_link_to(link, url, opts={})
  if current_resource.url == url_for(url)
    prefix = '<li class="active">'
  else
    prefix = '<li>'
  end
  prefix + link_to(link, url, opts) + "</li>"
end 

It’s used at the end of source/partials/_nav.erb like so

       <li class="dropdown">
            <%= link_to 'Projects <span class="caret"></span>', '#', {:class => 'dropdown-toggle', :data => {:toggle => 'dropdown'}} %>
           <ul class="dropdown-menu">
             <li><%= link_to 'Project A', '/projects/a.html' %></li>
             <li><%= link_to 'Project B', '/projects/b.html' %></li>
           </ul>
          </li>
          <%= nav_link_to 'Media', '/media.html' %>
          <%= nav_link_to 'Members', '/members.html' %>

FYI I just remembered my solution came from Issue #303