Getting the current route or URI

In my _nav partial, I need to conditionally add a “active” class to a list element if I’m currently on that page. Is there a ruby way to do this… all the examples I’m finding are using some Rails helper… or does Middleman have this info accessible?

I too, would be interested in how to accomplish this.

You can access the current page’s URL via current_page.url.

Inside your config.rb:

helpers do
  def nav_link(title, path, options = {})
    options[:class] = (options[:class] or '').split(' ')
    options[:class] << 'active' if current_page?(path)
    options[:class] = options[:class].join(' ')
    
    link = link_to(title, path)
    content_tag(:li, link, options)
  end

  def current_page?(path)
    current_page.url.chomp('/') == path.chomp('/')
  end
end

Inside your layout.erb:

    <ul>
      <%= nav_link "My page", "/about/page", class: "optional classes" %>
    </ul>

Thanks! That worked!

I do this to my partial “_nav.erb” based on Bootstrap 4 navigation and work fine:

    <ul>
       <li class="nav-item<%= " active" if current_page.data.title == "Homepage" %>">
          <%= link_to "Homepage", "/", title: "Homepage", class: "nav-link" %>
          <% if current_page.data.title == "Homepage" %>
             <span class="sr-only">(current)</span>
          <% end %>
       </li>
       <li class="nav-item<%= " active" if current_page.data.title == "About Us" %>">
          <%= link_to "About Us", "/pages/about.html", title: "About Us", class: "nav-link" %>
          <% if current_page.data.title == "About Us" %>
             <span class="sr-only">(current)</span>
          <% end %>
       </li>
       <li class="nav-item<%= " active" if current_page.data.title == "News" %>">
          <%= link_to "News", "/pages/news.html", title: "News", class: "nav-link" %>
          <% if current_page.data.title == "News" %>
             <span class="sr-only">(current)</span>
          <% end %>
       </li>
       <li class="nav-item<%= " active" if current_page.data.title == "Post" %>">
          <%= link_to "Post", "/pages/post.html", title: "Post", class: "nav-link" %>
          <% if current_page.data.title == "Post" %>
             <span class="sr-only">(current)</span>
          <% end %>
       </li>
       <li class="nav-item<%= " active" if current_page.data.title == "Contact" %>">
          <%= link_to "Contact", "/pages/contact.html", title: "Contact", class: "nav-link" %>
          <% if current_page.data.title == "Contactt" %>
             <span class="sr-only">(current)</span>
          <% end %>
       </li>
    </ul>