在JS脚本中使用Django模板标签是否可行?

3
我正在实现Google Maps API,我希望在模板首次呈现时打开第一个标记的InfoWindow,但仅当满足特定条件时才打开。
我有类似以下代码:
{% 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 %}

在Firefox或Internet Explorer 7中,这不会引发错误; 它做到了我想要的 - 但它似乎是错误的。我的文本编辑器正在警告/错误中尖叫。

这是不好的编码实践吗?如果是,有替代建议吗?


这是完整的代码,在脚本标记内,并编辑掉了不相关的部分:

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);
1个回答

6

在Javascript代码块中使用Django模板标签并没有什么问题。Django的模板语言大多数情况下是与语言无关的:它不关心模板化文本的含义。

我有很多带有标签、条件语句、变量替换等内容的Javascript代码。

你还可以选择插入一个Javascript布尔变量,并将条件放在Javascript中:

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

//...

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

我认为这样可以使 JavaScript 代码更简洁。你需要根据自己的代码来决定哪种风格更适合。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接