Active menu highlighting in Yii views or layout

Standard

One of the most common thing one need to do while developing a website is to highlight the currently selected menu item in main navigation. Essentially what you need to do is to check if the current URL and link to a given menu is same. If they match then we need to apply a CSS class to given menu so it’s shown differently from other menu items.

Below is how you can do it in Yii framework. I have created a small function below which checks the current URL and the URL of menu. If they match then it returns true else it returns false.

I usually create a utility class in which I include all utility functions like this one. I place this class underĀ componentsĀ and use it across the project. Now this is what the above mentioned function does.

  1. It first checks if the URL is of a static page or of a standard controller action.
  2. If it’s not for a static page then it compares the current controller and action with the passed controller and action. If they match then it returns true to the calling view/layout to notify this menu need to be highlighted. If not, it returns false.
  3. If page is also passed as an argument then it means it’s for a static page. In this case we also compare another URL parameter ‘view’ along with controller and action to ensure we are highlighting the correct page menu.

This function won’t work in itself since it need support from view/layout when our menu is. Below is sample code for how it should be used.

Here I have create three menu items. First is the ‘Home’ menu which links to site’s index page. Second is a link to static page called ‘faq’ and third is a link to post details. This function has limitations like it currently checks only for controller and action and does not consider if there are more URL arguments depending on which menu may be different. However it should give you a fair idea of how active menu highlighting works in Yii and it’s not difficult to extend it to make it work for more complex URLs. Enjoy!