Many months ago I had the same problem as you, and "googling" I found working code, and I adapted it to my needs. Here we go:
1 - We need to define a TWIG extension. We created the folder structure Your \ OwnBundle \ Twig \ Extension, if you have not decided yet.
2 - Inside this folder, we create the ControllerActionExtension.php file, whose code is:
namespace Your\OwnBundle\Twig\Extension; use Symfony\Component\HttpFoundation\Request; class ControllerActionExtension extends \Twig_Extension { protected $request; protected $environment; public function setRequest(Request $request = null) { $this->request = $request; } public function initRuntime(\Twig_Environment $environment) { $this->environment = $environment; } public function getFunctions() { return array( 'get_controller_name' => new \Twig_Function_Method($this, 'getControllerName'), 'get_action_name' => new \Twig_Function_Method($this, 'getActionName'), ); } public function getControllerName() { if(null !== $this->request) { $pattern = "#Controller\\\([a-zA-Z]*)Controller#"; $matches = array(); preg_match($pattern, $this->request->get('_controller'), $matches); return strtolower($matches[1]); } } public function getActionName() { if(null !== $this->request) { $pattern = "#::([a-zA-Z]*)Action#"; $matches = array(); preg_match($pattern, $this->request->get('_controller'), $matches); return $matches[1]; } } public function getName() { return 'your_own_controller_action_twig_extension'; } }
3 - After that, we need to specify the service for TWIG recognition:
services: your.own.twig.controller_action_extension: class: Your\OwnBundle\Twig\Extension\ControllerActionExtension calls: - [setRequest, ["@?request="]] tags: - { name: twig.extension }
4 - Clear the cache to make sure everything is in order:
php app/console cache:clear
5 - And now, if I forget nothing, you can access these two methods in the TWIG template: get_controller_name() and get_action_name()
6 - Examples:
You are in the {{ get_action_name() }} action of the {{ get_controller_name() }} controller.
This will output something like: you are in the default controller index action.
You can also use to check:
{% if get_controller_name() == 'default' %} Whatever {% else %} Blablabla {% endif %}
And it's all! Hope I helped you buddy :)
Edit: Take care of caching cleanup. If you do not use the --no-warmup option, you may realize that nothing is displayed in your templates. This is because this TWIG extension uses a query to retrieve the names Controller and Action. If you "warm up" the cache, the request does not match the browser request, and the methods may return '' or null