Wynn Netherland changelog.com/posts

navigasmic: Semantic navigation for Rails

Site navigation isn’t rocket surgery. But how many times have you gone down this route? You plop that <ul> into your header and then add <li>’s with each of your site navigation links. Then you need to make one of them highlighted based on the current page. Suddenly your nice clean view code gets a lot less readable as you handle conditional logic for setting the highlighted state, not to mention any sub navigation for the selected item. Try as you might to pull as much code into view helpers as you can, straddling the line between Haml or ERB and Ruby helpers never quite seems like a clean fit.

Jeremy Jackson has created an elegant solution with Navigasmic which aims to be simple, customizable, and pleasant to use while using less code than it generates. It features:

  • A clean API, leading to cleaner views
  • Support for Haml and ERB
  • Nested site navigation
  • Highlighted states
  • Disabled states
  • XML sitemaps


To install Navigasmic, configure the gem in your Gemfile

gem "navigasmic"

… and run

bundle install

In your view, use the semantic_navigation helper method to build your navigation. Here’s an example:

- semantic_navigation :main do |n|
  = n.group 'Media', :html => {:class => 'media'} do
    = n.item 'Image Gallery', :link => {:controller => 'media/images'}
    = n.item 'Videos', :link => {:controller => 'media/videos'}
  = n.group 'Info' do
    = n.item 'About Us', :link => '/about_us', :html => {:title => 'we are the coolest'}
    = n.item 'Nothing Here'

This produces the following HTML:

<ul id="main" class="primary semantic-navigation">
  <li id="media" class="with-group">
      <li id="image_gallery"><a href="/media/images"><span>Image Gallery</span></a></li>
      <li id="videos"><a href="/media/videos"><span>Videos</span></a></li>
  <div class="secondary">
    <li id="info" class="with-group">
        <li id="about_us">
          <a href="/about_us"><span>About Us</span></a>
            <li id="nothing_here"><span>Nothing Here</span></li>


One of the most powerful Navigasmic features is the range of highlighting options:

- semantic_navigation :main do
  = n.item 'Image Gallery', :link => 'media/images'
          :highlights_on => [{:controller => 'media'}, /images/, proc { Time.now.wday == 1 }]

Simply pass an array of options as :highlights_on including url_for options, strings, Regexes, even Ruby procs. If the highlighting criteria is met, the <li> gets a highlighted CSS class:

  <ul id="main" class="semantic-navigation">
    <li id="image_gallery" class="highlighted"><a href="/media/images"><span>Image Gallery</span></a></li>

Be sure and check the Readme for advanced usage including disabling options, XML sitemaps, and more.

[Source on GitHub]


Sign in or Join to comment or subscribe

Player art
  0:00 / 0:00