简体   繁体   中英

Symfony2, how to render controller's action in a twig template if 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 appears when the Controller has injected properties. Is there a way to use Twig's render(controller()) function with Controllers that have a constructor?

When I try following:

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

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

Constructor for this Controller look like that:

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

Injection of the container and someService is configured in service.yml.

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

UPDATE

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

UPDATE 2

Service definition from service.yml

some.controller:
    class: SomeBundle\Controller\SomeController
    arguments: ["@service_container", "@some.service"]

If you have defined your controller as a service, you need to "inject" it into twig in order to make it available and correctly instantiated.

I suggest to create twig global 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 could create a twig extension where you could inject your service in order to make it available for views

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

So it would be...

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

If you are Symfony 2.4+ you can make use of the request_stack to get the request rather than passing it in as an argument like..

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM