symfony - How to concatenate a Twig variable in Javascript -
i have twig
template contains javascript
code. in control pass array template. i'm using javascript
display map using google maps api javascript
. created variable incremented @ each loop round when creating markers. variable want use variable access each element of table according given index. since array in twig, index in javascript. concatenation seems complicated.
here's line concerned question :
infowindow.setcontent('<div><strong>{{ services['+j+']["name"] }}</strong><br>');
and here' full example:
var j = 0; var markers = locations.map(function(location, i) { var marker = new google.maps.marker({ position: location }); service.getdetails( { placeid: 'chijn1t_tdeuemsrusoyg83fry4' }, function(place, status) { google.maps.event.addlistener(marker, 'click', function() { infowindow.setcontent('<div><strong>{{ services['+j+']["name"] }}</strong><br>'); infowindow.open(map, this); }); }); j++; return marker; });
the browser (where javascript executed) won't know twig involved, because @ point whole twig code rendered plain html/css/javascript. therefore isn't possible use javascript manipulate twig rendering.
instead could
1. pass whole services array javascript
that (array passed in line 2 , line of infowindow.setcontent
using javascript array now):
var j = 0; var services = {{ services|json_encode|raw }}; var markers = locations.map(function(location, i) { var marker = new google.maps.marker({ position: location }); service.getdetails( { placeid: 'chijn1t_tdeuemsrusoyg83fry4' }, function(place, status) { google.maps.event.addlistener(marker, 'click', function() { infowindow.setcontent('<div><strong>' + services[j]["name"] + '</strong><br>'); infowindow.open(map, this); }); }); j++; return marker; });
problem here is, literally pass whole services array client. if huge or contains sensible information, should not that. instead should @ solution 2:
2. pass adapted service_names array javascript
where render twig template pass service_names
array:
$twig->render('the_template.twig', [ 'services' => $services, 'service_names' => array_column($services, 'name') ]);
then adapt solution answer 1 accordingly:
var j = 0; var service_names = {{ service_names|json_encode|raw }}; var markers = locations.map(function(location, i) { var marker = new google.maps.marker({ position: location }); service.getdetails( { placeid: 'chijn1t_tdeuemsrusoyg83fry4' }, function(place, status) { google.maps.event.addlistener(marker, 'click', function() { infowindow.setcontent('<div><strong>' + service_names[j] + '</strong><br>'); infowindow.open(map, this); }); }); j++; return marker; });
wiki
Comments
Post a Comment