3

我正在实施Google Maps API,并且希望在模板第一次呈现时打开第一个标记的InfoWindow,但只有如果某个条件成立,则为可以在JS脚本中使用Django模板标签

我有这样的事情:

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

回答

5

有什么不妥使用Javascript的丛内Django模板标签。 Django的模板语言大部分是语言不可知的:它不关心模板文本的含义。

我得到了大量的标签,条件,变量替代等Javascript河流。

您的其他选项这样的事情是插入一个Javascript布尔变量,并把有条件在Javascript:

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

//... 

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

我想这保证JavaScript清洁。你必须根据你自己的代码来决定你喜欢哪种风格。