Question

In my app in layout i have such code:

%li
   = link_to "Новости", all_articles_path(id: 1)
%li
   = link_to "Тест-драйвы", all_articles_path(id: 2)
%li
   = link_to "VIP-объявления", advanced_search_show_path(by_vip: true)

and for example if i go to url "all_articles_path(id: 1)" i need to add class to link "active", but how could i do this? i have only ideas with:

- if request.original_url.include? ("all_articles/1")
  = link_to "Новости", all_articles_path(id: 1), class: "active"

but i think that this is a bad idea, maybe there are any other more pretty solve of this problem?

Was it helpful?

Solution 2

There's a better way: active_link_to

This gem is amazing - you just have to use the = active_link_to "link", path() helper, and it will give an active class. We used it in a commercial app, and it worked out of the box

It's better than the current_page? method by far


Update

As per the comments, conditional styling would be something like this:

<% if defined?(params[:by_vip]) || defined?(params[:other])  %>
  <% active_class = "active" %>
<% end %>

<%= link_to "your_link, "#", class: active_class %>

Yes, it's basic & it can be put into a helper, but I hope it shows you what you can do!

OTHER TIPS

Use rails' current_page? method for this

class: <%= "active" if current_page?(all_articles_path) %>

To use this approach in HAML you may use string interpolations:

class: "#{'active' if current_page?(all_articles_path)}"

Better we write a helper method to know whether link is active or not to add a class:--

  = link_to "Новости", all_articles_path(id: 1), :class => is_article_link_active?(1) ? "active" : ""

Add following method to your helper file.

def is_article_link_active?(id)
  request.path.include?(all_articles_path(id: id)) 
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top