Search code examples
phphtmlphalcon

Trying to make current link active with helpers using Phalcon


I'm using Phalcon and trying to get the navigation item for each page of my web app to show active depending on whether or not the user is on that view. I'm using ActiveHelper.php to call a static function.

ActiveHelper.php:

public static function isActive($route){

    if ($route == $this->router->getRewriteUri()){
      echo "active";
    }

layout/public.volt:

<a href="{{ url('home') }}" class="<?php ActiveHelper::isActive('/home/'); ?>">Home</a>
<a href="{{ url('basicinfo') }}" class="<?php ActiveHelper::isActive('/basicinfo/'); ?>">Basic Info</a>

This doesn't seem to work though, however this does:

 <a href="{{ url('home') }}" class="
<?php 
   $route = '/home/';
   if ($route == $this->router->getRewriteUri()){
      echo 'active';
    } 
?>">Home</a>

when echoing $this->router->getRewriteUri(); i get the current page such as '/home/' or '/basicinfo/'


Solution

  • public static function isActive($route){
    
        if ($route == $this->router->getRewriteUri()){
          return "active";
        }
        // ...
        return "";
    

    in the layout view:

    <a href="{{ url('home') }}" class="<?php echo $currentUri=='/home/'?'active':'' ?>">Home</a>
    

    Edit: In the BaseController where you have access to $router you can set a variable that will be injected into the layout called $currentUri and you could check this instead, this way the code wont be called over and over again and a variable will have the value in it to check against. Remove the isActive function call from the layout and pass a variable into the view.