Question

I have a Site Layout with a top nav bar, I need to set the class to active depending on the controller which changes when the user clicks on different pages.

views->index.phtml

 <li class='<?php echo (isset($this->controllerName) && $this->controllerName == 'about') ? 'active' : '' ?>'><a href="/about">About Us</a></li>
 <li class='<?php echo (isset($this->controllerName) && $this->controllerName == 'services') ? 'active' : '' ?>'><a href="/services">Member Sevices</a></li>

I was hoping that Phalcon had a view function or maybe something I can put in the bootstrap so it worked for all pages with out me having to remember to set the controllerName variable in each Controller manually.

Was it helpful?

Solution

Inside your view access your router service :

$this->router->getControllerName()
$this->router->getActionName()

or if you are using volt you can use the short hand

router.getControllerName()
router.getActionName()

That will work for your use case, but if you find that your menu logic becomes too unwieldy, there are several methods to achieve what you are attempting to do.

The easiest I find is to use javascript, but that doesn't have a fallback if they have js disabled(1%). If you want to cover 100% of your audience you could use a method like the Phalcon team did in INVO using an element library: https://github.com/phalcon/invo/blob/master/app/library/Elements.php

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top