1

I have a Rails app with Twitter Bootstrap installed. Bootstrap encapsulates each navigation bar link in a HTML list element, like so:

<ul class="nav">
    <li><a href="#home">Home</a></li>
    <li><a href="#products">Products</a></li>
    <li><a href="#settings">Settings</a></li>
</ul>

When a link is the current page, Bootstrap allows you to highlight it by setting the list element's class (not the link itself) to "active", like so:

    <li class="active"><a href="#products">Products</a></li>

My question is: how do you set the list element's class to "active" (if it is the current page) programmatically using Rails?

I know how it can be done for a link. Example:

<%= link_to "Products", products_path, :class => "active" if current_page?(:controller => "products") %>

But I don't know how it can be done for the parent list element.

1 Answer 1

2

Use the content_tag helper:

<%= content_tag :li, :class => 'active' do %>
  List item contents
<% end %>
Sign up to request clarification or add additional context in comments.

2 Comments

But how to set the class to "active" only if it is the current page? I tried <%= content_tag :li, :class => 'active' if current_page?(:controller => "products") do %> but that doesn't work.
Ah, figured it out. Needs to be: <%= content_tag :li, :class => ('active' if current_page?(:controller => "products")) do %>. In other words, the class' value needs to be encapsulated in parentheses. @georgebrock can you update your answer to reflect this?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.