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?
I would highly suggest creating a helper method called
visited_classor 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:
Then, in your view/HAML file, simply call
visited_classand 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 therequest.request_uri, but that might be a bit more tedious.