Il faut d’abord commencer par créer la classe dans Acme\Bundle\AcmeBundle\Twig\Extension
<?php namespace Acme\Bundle\AcmeBundle\Twig\Extension; use Symfony\Component\HttpFoundation\Request; class AcmePageExtension extends \Twig_Extension { protected $request; /** * * @var \Twig_Environment */ protected $environment; public function __construct(Request $request) { $this->request = $request; } public function initRuntime(\Twig_Environment $environment) { $this->environment = $environment; } public function getFunctions() { return array( 'getControllerName' => new \Twig_Function_Method($this, 'getControllerName'), 'getActionName' => new \Twig_Function_Method($this, 'getActionName'), ); } /** * Get controller name */ public function getControllerName() { $regexp = "#Controller\\\([a-zA-Z]*)Controller#"; $results = array(); preg_match($regexp, $this->request->get('_controller'), $results); return strtolower($results[1]); } /** * Get action name */ public function getActionName() { $regexp = "#::([a-zA-Z]*)Action#"; $results = array(); preg_match($regexp, $this->request->get('_controller'), $results); return $results[1]; } public function getName() { return 'acme_page'; } }
Ensuite, il faut créer le service dans services.xml
<parameters> <parameter key="acme.enhance.twig.class">Acme\Bundle\AcmeBundle\Twig\Extension\AcmePageExtension</parameter> </parameters> <services> <service id="request" class="Symfony\Component\HttpFoundation\Request" /> <service id="acme.enhance.twig" class="%acme.enhance.twig.class%"> <tag name="twig.extension" /> <argument type="service" id="request" /> </service> </services>
Pour connaitre le nom du controller ou de l’action, il suffit de faire :
{{ getControllerName() }} ou {{ getActionName() }}