Get controller name in TWIG template

I am learning symfony2.3 and I get an error message when I try to get the controller name in the branch template.

Controller:

namespace Acme\AdminBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Request; class DefaultController extends Controller { public function indexAction($name) { return $this->render('AcmeAdminBundle:Default:index.html.twig', array('name' => $name)); } } 

In my TWIG template:

 {% extends '::base.html.twig' %} {% block body %} {{ app.request.get('_template').get('controller') }} Hello {{ name }}!!! {% endblock %} 

Output:

 Impossible to invoke a method ("get") on a NULL variable ("") in AcmeAdminBundle:Default:index.html.twig at line 3 

I want the output to be like "Default"

I use symfony 2.3, I also tried using symfony 2.1, but the same error occurs on both versions.

+6
source share
7 answers

use this line to display the controller name in the branch:

 {{ app.request.attributes.get("_controller") }} 
+18
source

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; /** * A TWIG Extension which allows to show Controller and Action name in a TWIG view. * * The Controller/Action name will be shown in lowercase. For example: 'default' or 'index' * */ class ControllerActionExtension extends \Twig_Extension { /** * @var Request */ protected $request; /** * @var \Twig_Environment */ 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'), ); } /** * Get current controller name */ 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]); } } /** * Get current action name */ 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 --no-warmup 

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

+16
source

Since Symfony 3.x, the service request is replaced by request_stack, and the Twig Extension declaration is changed from Twig 1.12.

I will correct Dani's answer ( fooobar.com/questions/947832 / ... ):

1 - We need to define a TWIG extension. We created the folder structure AppBundle \ Twig \ Extension, if you have not decided yet.

2 - Inside this folder, we create the ControllerActionExtension.php file, whose code is:

 <?php namespace AppBundle\Twig\Extension; use Symfony\Component\HttpFoundation\RequestStack; class ControllerActionExtension extends \Twig_Extension { /** @var RequestStack */ protected $requestStack; public function __construct(RequestStack $requestStack) { $this->requestStack = $requestStack; } public function getFunctions() { return [ new \Twig_SimpleFunction('getControllerName', [$this, 'getControllerName']), new \Twig_SimpleFunction('getActionName', [$this, 'getActionName']) ]; } /** * Get current controller name * * @return string */ public function getControllerName() { $request = $this->requestStack->getCurrentRequest(); if (null !== $request) { $pattern = "#Controller\\\([a-zA-Z]*)Controller#"; $matches = []; preg_match($pattern, $request->get('_controller'), $matches); return strtolower($matches[1]); } } /** * Get current action name * * @return string */ public function getActionName() { $request = $this->requestStack->getCurrentRequest(); if (null !== $request) { $pattern = "#::([a-zA-Z]*)Action#"; $matches = []; preg_match($pattern, $request->get('_controller'), $matches); return $matches[1]; } } public function getName() { return 'controller_action_twig_extension'; } } 

3 - After that, we need to specify the service for TWIG recognition:

 app.twig.controller_action_extension: class: AppBundle\Twig\Extension\ControllerActionExtension arguments: [ '@request_stack' ] tags: - { name: twig.extension } 

4 - Clear the cache to make sure everything is in order:

 php bin/console cache:clear --no-warmup 

5 - And now, if I forget nothing, you can access these two methods in the TWIG template: getControllerName () and getActionName ()

6 - Examples:

You are in the action {{getActionName ()}} of the controller {{getControllerName ()}}.

This will output something like: you are in the default controller index action.

You can also use to check:

 {% if getControllerName() == 'default' %} Whatever {% else %} Blablabla {% endif %} 
+5
source

I really don't see WHY you need it.
You could better send parameters to your opinion.

But if you really need it, here is the solution:

Your error comes from the second get method

 request = app.request // Request object NULL = request.get('_template') // Undefined attribute, default NULL NULL.get('controller') // Triggers error 

If you want to receive a controller call during a request, you can access it through the request attribute _controller key

 app.request.attribute.get('_controller') 

Will return

 Acme\AdminBundle\Controller\DefaultController::indexAction 

Then you can disassemble it the way you want.

Note that this does not return a controller instance, only its name and method are called

+1
source

To get the controller - {{app.request.attributes.get ('_ controller')}} To get the action - {{app.request.attributes.get ('_ template'). Get ('name')}}

Found at - http://forum.symfony-project.org/viewtopic.php?f=23&t=34083

0
source

It can change. If you use annotations in the controller, for example. @Template("AcmeDemoBundle:Default:index") , trying to access app.request.get('_template') in your Twig template will return a string, for example. "AcmeDemoBundle: Default: index." Therefore, you may need to access it as follows:

 {% set _template = app.request.get('_template')|split(':') %} {% set controller = _template[1] %} {% set bundle = _template[0] %} 

If you are not using annotations, you can use app.request.get('_template').get('_controller')

0
source

Controller:

 {{ app.request.attributes.get('_template').get('controller') }} 

Act:

 {{ app.request.attributes.get('_template').get('name') }} 

enjoy;)

-1
source

Source: https://habr.com/ru/post/947832/


All Articles