Is it possible to use a Django template template inside a JS script

I am implementing the Google Maps API, and I would like the first InfoWindow token to open when the first template renderer, but only if a certain condition is met.

I have something like this:

{% if project %}
//the following is automatically open the infowindow of the FIRST marker in the array when rendering the template
  var infowindow = new google.maps.InfoWindow({
    maxWidth:500
  });
  infowindow.setContent(markers[0].html);
  infowindow.open(map, markers[0]);
{% endif %}

This does not cause errors in Firefox or Internet Explorer 7; he does what I want - but it's just WRONG. My text editor shouts its head with warnings / errors.

Is this bad coding practice? And if so, any suggestions for an alternative?


This is the complete code, inside script tags, with edited irrelevant bits:

function initialize() {
  ...
  var map = new google.maps.Map(document.getElementById("map_canvas"),
                                myOptions);

  var markers = []
  setMarkers(map, projects, locations, markers);
  ...
}

function setMarkers(map, projects, locations, markers) {
  for (var i = 0; i < projects.length; i++) {
    var project = projects[i];
    var address = new google.maps.LatLng(locations[i][0],locations[i][1]);

    var marker = new google.maps.Marker({
            map: map, 
            position:address,
            title:project[0],
            html: description
        });

    markers[i] = marker;
    google.maps.event.addListener(marker, 'click', function() {
           infowindow.setContent(this.html);
              infowindow.open(map,this);
    });
  }

{% if project %}
//the following is automatically open the infowindow of the FIRST marker in the array when rendering the template
  var infowindow = new google.maps.InfoWindow({
    maxWidth:500
  });
  infowindow.setContent(markers[0].html);
  infowindow.open(map, markers[0]);
{% endif %}

 })
}

google.maps.event.addDomListener(window, 'load', initialize);
+3
1

Django Javascript. Django : , .

Javascript , , ..

- Javascript Javascript:

<script>
var is_project = {% if project %}true{% else %}false{% endif %};

//...

if (is_project) {
    // stuff for project
}
</script>

, Javascript . , , .

+5

Source: https://habr.com/ru/post/1771990/


All Articles