Search code examples
rubyruby-on-rails-4slim-lang

Rails print navigation bar using loop and highlight button leading to current page


I'm newbie on rails.

I would like to create nav bar like here on top of page. "CSS" button is highlighted, because it leads to current page.

I would like to store paths and button titles in some place. Arrays would be ok I guess?

For example:

paths = ['root_path', 'articles_path']
titles = ['Home', 'Articles list']

Using those two arrays I would be able to print nav bar using one loop. I could easily remove or add items to it. Also I could include condition inside loop, so button leading to current page would have some html class attached (Changing it's background).

Where should I put those arrays? Is there better/more intelligent way to achieve same thing?

P.S. I don't want to use javascript.


Solution

  • It is better to use hash.

    Declare a ruby hash with a name say "nav_bars"

    @nav_bars = { "Home": "root_path", "Articles_list": "articles_path" }
    

    Then you can loop over the hash in your views as

    <% @nav_bars.each do |key, value|%>
        <h3> <%= link_to key, value %> </h3
    <% end%>