simple rails helper for bootstrap3 nav-pill

Bootstrap3 has a nice little nav-pill device. 

(Bootstrap2 does too and it may work the same, but I did this with bootstrap3, and am putting bootstrap3 in the text so people googling will find it. Googling bootstrap solutions gets harder now that there are versions that work differently and you want a solution for your version.)

In Rails, you’re going to want to mark the right link as ‘active’; bootstrap3 needs you to set a class on the <li>, not the <a> for this.  And also requires that even the active link be an actual <a> tag — not a non-clickable <span> as I’ve often used before. Both of these mean that Rails little-known-but-useful `#link_to_unless` isn’t going to be helpful. Fortunately, link_to_unless is implemented in terms of the even-less-known-but-even-more-flexible #current_page?

Here’s a very simple helper method you could put in your `application_helper` to generate the <li><a>…</a></li> inside a bootstrap3 <ul class=”nav nav-pills”>, appropriately marking a link active if it’s link params match the current page.

  # helper to make bootstrap3 nav-pill <li>'s with links in them, that have
  # proper 'active' class if active.
  # the current pill will have 'active' tag on the <li>
  # html_options param will apply to <li>, not <a>.
  # can pass block which will be given to `link_to` as normal.
  def bootstrap_pill_link_to(label, link_params, html_options = {})
    current = current_page?(link_params)

    if current
      html_options[:class] ||= ""
      html_options[:class] << " active "

    content_tag(:li, html_options) do
      link_to(label, link_params)

You call it the same way you call Rails link_to, eg `bootstrap_pill_link_to(some_label, some_url_or_params)`

It could be made even fancier to do argument arity checking to support a &block on the link_to instead of a string label, etc. But I didn’t need that, this does the job.

It does leave the active link as a fully clickable nav link. I’m used to making the active link a non-clickable span instead, but bootstrap3’s nav-pill would make that tricky, which made me realize it’s probably fine or even better UX as a clickable link anyway. (Among other things, it means you can right-click it to bookmark it or whatever, even though it’s active. I dunno).

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s