问题
Should it work in Silex with symfony/twig-bridge ?
{{ render(controller('MyController')) }}
Now I have message like this:
Twig_Error_Syntax: The function "controller" does not exist in "...
回答1:
I've found this working:
{{ render(controller('services.controller:action', {[params]}) }}
And you can define the controller as a service:
$app['services.controller'] = function() use ($dependecy1, .., $dependencyN){
return new \\PathToYourControllerClass($dependecy1, .., $dependencyN);
}
回答2:
You can use it this way:
{{ render(path('your_route_id', {'id': id, 'anotherParam': param})) }}
回答3:
I've found this working :
{{ render(controller('Full\\Namespace\\To\\Your\\Controller::listAction')) }}
please don't forget a double slash '\\'
Example:
{{ render(controller('Acme\\ProductController::listAction')) }}
In Your ProductController (I'm using Doctrine 2 in this example) :
public function listAction(Application $application)
{
$em = $application['orm.em'];
$produits = $em->getRepository('Acme\Entity\Produit')->findAll();
return $application['twig']->render('list.html.twig', array(
'products' => $products
));
}
Then in your list.html.twig
{% for product in products %}
<h2> {{ product.name }} </h2>
{% endfor %}
来源:https://stackoverflow.com/questions/21417672/how-to-insert-a-controller-in-twig-with-render-in-silex