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清潔。你必須根據你自己的代碼來決定你喜歡哪種風格。