Skip to content

Instantly share code, notes, and snippets.

@zemd
Created December 11, 2015 19:00
Show Gist options
  • Save zemd/2d074556658dc88f1607 to your computer and use it in GitHub Desktop.
Save zemd/2d074556658dc88f1607 to your computer and use it in GitHub Desktop.
Twig function extension for router checker
<li class="menu{% if (is_route_active('homepage')) %} active{% endif %}">
<a href="{{ path('homepage') }}">Main page</a>
</li>
<?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;
}
}
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