Is it possible to write symfony2 and template expressions regarding a package?

Take, for example, the following controller / action:

public function indexAction() { return $this->render('TestBundle:TestController:index.html.twig'); } 

I would like to write a template expression (or whatever the name is) as follows:

 public function indexAction() { return $this->render('*:TestController:index.html.twig'); } 

So symfony knows that I am looking for a template in this very package. To write the entire Owner + Bundle for each / action / repository template that I want to name is very annoying. Moreover, most of the time I relate to actions and templates in one set.

NOTE. I know that templates can be hosted at the application level and referenced as follows:

 '::index.html.twig' 

But that is not what I need.

+4
source share
1 answer

This is possible with a bit of custom code.

Basically, you want to override the render() controller method and enable logic to extract the name of the current package.

Note that instead of my controllers extending Symfony\Bundle\FrameworkBundle\Controller\Controller , they extend the user controller (which then extends the Symfony controller). This allows you to conveniently give the controller more options by adding your own methods.

Example: MyBundle\Controller\MyController\ extends MyCustomBaseController , which continues to Symfony\Bundle\FrameworkBundle\Controller\Controller .

So, in my user controller, I have two methods:

 public function render($view, array $parameters = array(), Response $response = null) { $currentBundle = $this->getCurrentBundle(); $view = str_replace('*', $currentBundle, $view); return parent::render($view, $parameters, $response); } public function getCurrentBundle() { $controller = $this->getRequest()->attributes->get('_controller'); $splitController = explode('\\', $controller); return $splitController[1]; } 

Take a look at render() . It extracts the current package name and uses it to create the $view variable. Then it just calls parent::render() and it is as if you manually defined the package name in the rendering expression.

The code here is very simple, so you can easily extend it to do other things, for example, you can also not enter the name of the controller.

Important: If you use a user controller, make sure you use Symfony\Component\HttpFoundation\Response , otherwise PHP will complain that the method signatures for render() do not match.

0
source

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


All Articles