Reputation: 2057
I have this Haml view:
!!! strict
%html{:xmlns => "http://www.w3.org/1999/xhtml"}
%head
%meta{:content => "text/html; charset=utf-8", "http-equiv" => "Content-Type"}
%title
Lighty | #{@page_title || "Home"}
%body
#popup Login here
#fade
#wrapper
#container
#header
%a#logo{:href => "/"}
#menu
%ul#main
%li#lighty
%a{:href => "/"} Lighty
%ul
%li
%a Link here
%li#community
%a{:href => "/community"} Community
#content
And I would like to add an if on line #16 to check if it is the currently visited page and add the class "active" to the li
if it returns true.
How do I write that if statement there and is there any easier way to do this?
My plan now is to use a variable like @current_page
and test if @current_page == "community"
and add a class if it returns true.
Am I thinking wrong? Is there any easier way to accomplish this?
Upvotes: 0
Views: 1290
Reputation: 64363
Add the visited_class
method suggested by Topher
to the app\helpers\application_helpers.rb
file. To add a class to the li
element, change your HAML as follows:
%li#lighty{:class => "#{visited_class('pages', 'show')}"}
%a{:href => "/"} Lighty
%ul
%li
%a Link here
Upvotes: 1
Reputation: 20667
I would highly suggest creating a helper method called visited_class
or something similar since it should have access to the current controller/action. Then, you can write all of the code's logic inside of the helper method. This keeps your views drastically cleaner.
You can place this in many places, but since I have so few helpers, I usually just drop it in ApplicationHelper:
def ApplicationHelper
def visited_class(controller, action)
if params[:controller] == controller && params[:action] == action
return " active"
else
return ""
end
end
end
Then, in your view/HAML file, simply call visited_class
and pass in the controller/action that you want to check. You might also be able to use a URL parameter and piece it together from the request.request_uri
, but that might be a bit more tedious.
Upvotes: 2