Cela se fait avec la symphonie 3.4, mais probablement quelque chose de similaire peut être fait avec SF2.
src\AppBundle\Twig\AppExtension.php
<?php
namespace AppBundle\Twig;
use Symfony\Component\HttpFoundation\RequestStack;
class AppExtension extends \Twig_Extension
{
private $requestStack;
public function __construct(RequestStack $requestStack)
{
$this->requestStack = $requestStack;
}
public function getFunctions()
{
return [
new \Twig_SimpleFunction('activeMenu', [$this, 'activeMenu'])
];
}
/**
* Pass route names. If one of route names matches current route, this function returns
* 'active'
* @param array $routesToCheck
* @return string
*/
public function activeMenu(array $routesToCheck)
{
$currentRoute = $this->requestStack->getCurrentRequest()->get('_route');
foreach ($routesToCheck as $routeToCheck) {
if ($routeToCheck == $currentRoute) {
return 'active';
}
}
return '';
}
}
Ajouter ceci à services.yml
services:
#... some other services
AppBundle\Twig\AppExtension:
arguments: ["@request_stack"]
Utilisation :
<ul class="nav navbar-nav">
<li class="{{ activeMenu(['form', 'edit_form']) }}"><a href="{{ path('form') }}">Form</a></li>
<li class="{{ activeMenu(['list']) }}"><a href="{{ path('list') }}">List</a></li>
</ul>