Created
December 11, 2015 19:00
-
-
Save zemd/2d074556658dc88f1607 to your computer and use it in GitHub Desktop.
Twig function extension for router checker
This file contains 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
<li class="menu{% if (is_route_active('homepage')) %} active{% endif %}"> | |
<a href="{{ path('homepage') }}">Main page</a> | |
</li> |
This file contains 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 AppBundle\Twig\Extension; | |
use Symfony\Component\HttpFoundation\RequestStack; | |
use Twig_SimpleFunction; | |
class RouteChecker extends \Twig_Extension | |
{ | |
/** @var RequestStack */ | |
protected $requestStack; | |
public function __construct(RequestStack $requestStack) { | |
$this->requestStack = $requestStack; | |
} | |
/** | |
* Returns the name of the extension. | |
* | |
* @return string The extension name | |
*/ | |
public function getName() { | |
return 'route_checker'; | |
} | |
/** | |
* Returns a list of functions to add to the existing list. | |
* | |
* @return Twig_SimpleFunction[] | |
*/ | |
public function getFunctions() { | |
return [ | |
new Twig_SimpleFunction('is_route_active', [$this, 'isRouteActive']) | |
]; | |
} | |
public function isRouteActive($route) { | |
return $this->requestStack->getCurrentRequest()->get('_route') === $route; | |
} | |
} |
This file contains 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
app_router_checker.twig_extension: | |
class: AppBundle\Twig\Extension\RouteChecker | |
public: false | |
arguments: ["@request_stack"] | |
tags: | |
- { name: twig.extension } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment