Created
May 15, 2019 03:48
-
-
Save vaibhavpandeyvpz/50031cb265a188f027f867f83db3d552 to your computer and use it in GitHub Desktop.
Twig extension for rendering 'active' class depending on path or route.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Twig; | |
use Symfony\Component\HttpFoundation\RequestStack; | |
use Twig\Extension\AbstractExtension; | |
use Twig\TwigFunction; | |
class ActiveExtension extends AbstractExtension | |
{ | |
/** | |
* @var RequestStack | |
*/ | |
protected $requests; | |
public function __construct(RequestStack $requests) | |
{ | |
$this->requests = $requests; | |
} | |
public function activeClass(string $condition, string $class = 'active'): ?string | |
{ | |
$request = $this->requests->getCurrentRequest(); | |
$subject = $request->get('_route'); | |
if ($subject === $condition) { | |
return $class; | |
} | |
if (($subject !== null) && preg_match("#^$condition$#", $subject)) { | |
return $class; | |
} | |
$subject = $request->getPathInfo(); | |
if ($subject === $condition) { | |
return $class; | |
} | |
if (($subject !== null) && preg_match("#^$condition$#", $subject)) { | |
return $class; | |
} | |
return null; | |
} | |
public function getFunctions(): array | |
{ | |
return [ | |
new TwigFunction('active', [$this, 'activeClass']), | |
]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment