How to insert a Controller in Twig with “render” in Silex

社会主义新天地 提交于 2019-12-14 01:54:07

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!