简体   繁体   中英

Call twig template in JS

I have a json api with symfony2:

return new JsonResponse(array(
    'deliveryRange' => $deliveryRange,
    'html' => $this->render(':App:Command/deliveryRange.html.twig'),
));

The delivery range is an Array, the html variable send me back my twig template.

Here is my JS:

callDeliveryRange: function(){
    $.ajax({
        type: "POST",
        url: Command.routeApiRange,
        cache: false,
        data: {},

        success: function (data, status) {
            Command.htmlDeliveryRange(data);
        },
    })
},

htmlDeliveryRange: function(data){
    $('#content-delivery-range').html(data.html);
},

In the htmlDeliveryRange function I would like to append the twig template in my new twig file.

But nothing is happening.

And I would like also to use the variable of data.deliveryRange in the template.

Is it possible?

Use $this->renderView() instead of render() method. renderView() returns content of twig template as string, while render() returns Response object.

Try just:

return new JsonResponse([
   'deliveryRange' => $deliveryRange,
   'html'          => $this->renderView(':App:Command/deliveryRange.html.twig'),
]);

You need to do:

$lReturn['html'] = $this->renderView(':App:Command/deliveryRange.html.twig');
$lReturn['deliveryRange'] = $deliveryRange;

return new Response(json_encode($lReturn), 200, array('Content-Type'=>'application/json'));

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