开发者

Is it ok to use Django Template Tag inside JS script

开发者 https://www.devze.com 2023-01-22 16:21 出处:网络
I\'m implementing Google Maps API and I\'d like the first marker\'s InfoWindow to open when the template is first rendered but only if a certain condition is true.

I'm implementing Google Maps API and I'd like the first marker's InfoWindow to open when the template is first rendered but only if a certain condition is true.

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.Info开发者_开发百科Window({
    maxWidth:500
  });
  infowindow.setContent(markers[0].html);
  infowindow.open(map, markers[0]);
{% endif %}

This does not throw an error in Firefox or Internet Explorer 7; it does what I want - but it just SEEMS wrong. My text editor is screaming its head off with warnings/errors.

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


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

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);


There's nothing wrong with using a Django template tag inside a clump of Javascript. Django's templating language is for the most part language-agnostic: it doesn't care what the templated text means.

I've got rivers of Javascript with tons of tags, conditionals, variable substitutions, and so on.

Your other option for this sort of thing is to insert a Javascript boolean variable, and put the conditional in Javascript:

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

//...

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

I suppose this keeps the Javascript cleaner. You'd have to decide based on your own code which style you prefer.

0

精彩评论

暂无评论...
验证码 换一张
取 消