Symfony2 how to visualize the action of a controller in a branch template if the controller has a constructor

From the official documentation ( http://symfony.com/doc/current/quick_tour/the_view.html#embedding-other-controllers ) I learned how to embed a controller in a Twig template.

The problem occurs when the controller enters properties. Is there a way to use the Twig render(controller()) function with controllers that have a constructor?

When I try to do the following:

 {{ render(controller( 'SomeBundle:Some:renderList', { 'request': app.request } )) }} 

I get this error: Missing argument 1 for SomeBundle\Controller\SomeController::__construct()

The constructor for this controller is as follows:

 public function __construct($container, SomeService $someService) { parent::__construct($container); $this->someService = $someService; } 

Container injection and someService is configured in service.yml.

So, again, my question is: how to embed a controller in a Twig template when this controller uses Injection Dependency?

UPDATE

I could do this: {{ render(app.request.baseUrl ~ '/some/route') }} But I would like to avoid routes.

UPDATE 2

Service definition from service.yml

 some.controller: class: SomeBundle\Controller\SomeController arguments: ["@service_container", "@some.service"] 
+5
source share
2 answers

For controllers as a service, you just need to use the service name ( @some.controller ) and the action ( yourAction ) rather than the controller shortcut ( SomeBundle:Some:renderList ), as you can see in Sylius Templates .

So that would be ...

 {{ render(controller('some.controller:yourAction')) }} 

If you are Symfony 2.4+, you can use request_stack to get the request, rather than passing it as an argument, for example ..

 $request = $this->container->get('request_stack')->getMasterRequest(); 
+3
source

If you defined your controller as a service, you need to β€œinsert” it into the branch to make it accessible and correctly created.

I suggest creating a global twig variable

 #app/config/config.yml twig: globals: cc: "@comparison.controller" 

Then you can use one of the methods (actions?)

 {{ cc.foo(aBarVariable) }} 

Alternative answer

You can create a twig extension where you can add your service to make it viewable

+5
source

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


All Articles