Search code examples
jrubyjrubyonrails

jruby on Rails : How to highlight the current navigation bar list item which the page user currently in


I'm just trying jRuby on Rails for the first time.

In my project I'm having three pages under root/app/views/pages which I want to traverse in my navigation bar.

My navbar is

  <div class ="navbar">
        <ul>
            <li <%= class = is_active?("home") %> ><%= link_to 'Home', {:controller => 'pages', :action => 'home'} %></li>
            <li><%= link_to 'About Us', {:controller => 'pages', :action => 'about'} %></li>
            <li><%= link_to 'Contact Us', {:controller => 'pages', :action => 'contact'} %></li>
        </ul>
    </div>

My CSS file contains

    .navbar .active {
           background-color: #4CAF50;
           color: white;
    }

After some googling i created a helper

   module PagesHelper
      def is_active?(page_name)
          "active" if params[:action] == page_name
      end
   end

in project_root/app/helpers/pages_helper.rb so that I would get highlighted in the navigation bar item based on the page I'm currently in.

This gave me

app/views/layouts/application.html.erb:18: syntax error, unexpected '=' ...@output_buffer.append=( class = is_active?("home") );@output... ... ^ actionview (4.2.6) lib/action_view/template.rb:296:in module_eval' actionview (4.2.6) lib/action_view/template.rb:296:incompile' actionview (4.2.6) lib/action_view/template.rb:245:in block (2 levels) in compile!' activesupport (4.2.6) lib/active_support/notifications.rb:166:ininstrument' actionview (4.2.6) lib/action_view/template.rb:333:in instrument' actionview (4.2.6) lib/action_view/template.rb:244:inblock in compile!' actionview (4.2.6) lib/action_view/template.rb:232:in synchronize' actionview (4.2.6) lib/action_view/template.rb:232:incompile!' actionview (4.2.6) lib/action_view/template.rb:144:in block in render' activesupport (4.2.6) lib/active_support/notifications.rb:166:ininstrument'

Please help.


Solution

  • I found the answer. In my navbar div I had to use "class = " out from the <%= %> like this.

        <ul>
            <li class = <%= is_active?("home") %> ><%= link_to 'Home', {:controller => 'pages', :action => 'home'} %></li>
            <li class = <%= is_active?("about") %>><%= link_to 'About Us', {:controller => 'pages', :action => 'about'} %></li>
            <li class = <%= is_active?("contact") %>><%= link_to 'Contact Us', {:controller => 'pages', :action => 'contact'} %></li>
        </ul>