【问题标题】:Is it ok to use Django Template Tag inside JS script可以在 JS 脚本中使用 Django 模板标签吗
【发布时间】:2011-05-02 01:34:03
【问题描述】:

我正在实现 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);

【问题讨论】:

    标签: javascript django google-maps coding-style django-templates


    【解决方案1】:

    在一堆 Javascript 中使用 Django 模板标签并没有错。 Django 的模板语言在很大程度上与语言无关:它不关心模板文本的含义。

    我有大量的 Javascript,其中包含大量的标签、条件、变量替换等等。

    您对这类事情的另一个选择是插入一个 Javascript 布尔变量,并将条件放入 Javascript:

    <script>
    var is_project = {% if project %}true{% else %}false{% endif %};
    
    //...
    
    if (is_project) {
        // stuff for project
    }
    </script>
    

    我想这会使 Javascript 更干净。您必须根据自己的代码来决定您喜欢哪种风格。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-12
      • 1970-01-01
      • 1970-01-01
      • 2014-03-20
      • 1970-01-01
      • 1970-01-01
      • 2015-02-27
      • 1970-01-01
      相关资源
      最近更新 更多