gpt4 book ai didi

javascript - 如何将 jQuery 变量设置为 django 模板变量

转载 作者:行者123 更新时间:2023-11-28 16:27:48 25 4
gpt4 key购买 nike

我在 Django 模板中使用 jQuery 脚本来呈现 Google map 。目标是在 map 上绘制多个标记。我试过两件事:

  1. 将 jQuery var 设置为 Django 模板变量,我在 views.py 中将其定义为列表。在这种情况下无法产生任何标记。只是一张空白 map 。

    var markers = {{ marker_list }};

    我在页面上打印了marker_list来确认,这是我上次测试的:marker_list = [['清迈公园', 21.0333, 21.0333], ['胡志明陵', 21.036666667, 21.036666667]]

  2. 在 jQuery 脚本中使用模板标签创建一个 for 循环,并使用模板变量构建列表。这样一来,即使列表中有多个位置(请参阅上面的 marker_list),也只会绘制一个标记。

    {% 例如在查询集中 %}

    变量标记 = [ [{{ instance.place_id }}, {{ instance.place_lat }}, {{ instance.place_long }}]];

    {% endfor %}

下面显示了完整代码,显示了尝试 #2。请注意,javascript 中的“var markers”需要一个列表列表。即 var markers = [[name1, latitude1, longitude1], [name2, latitude2, longitude2]].

任何帮助将不胜感激。我既是 Django 又是 Javascript n00b。

views.py

def places_map(request):    
if request.user.is_authenticated():
queryset = AddLink.objects.filter(user=request.user)
marker_list = []

for instance in queryset:
name = str(instance.location)
latitude = float(instance.place_lat)
longitude = float(instance.place_lat)
marker_list += [[name, latitude, longitude]]

context = {
"queryset": queryset,
"marker_list": marker_list
}

return render(request, "places_map.html", context)
else:
raise Http404("You must be logged in to view places.")

places_map.html

{% extends "base.html" %}
{% load crispy_forms_tags %}
{% load staticfiles %}

<style>
{% block style %}

#map_wrapper {
height: 400px;
}

#map_canvas {
width: 100%;
height: 100%;
}

{% endblock style %}
</style>

{% block content %}

<div class='row' align='center'>
<h1 id="places-title">Map</h1>

{% if queryset %}
<!-- removed -->
{% endif %}
</div>

<div id="map_wrapper">
<div id="map_canvas" class="mapping"></div>
</div>

<!-- For testing -->
{{ marker_list }}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>

<script>
// Script from http://wrightshq.com/playground/placing-multiple-markers-on-a-google-map-using-api-3/

jQuery(function($) {
// Asynchronously Load the map API
var script = document.createElement('script');
script.src = "http://maps.googleapis.com/maps/api/js?sensor=false&callback=initialize";
document.body.appendChild(script);
});

function initialize() {
var map;
var bounds = new google.maps.LatLngBounds();
var mapOptions = {
mapTypeId: 'roadmap'
};

// Display a map on the page
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
map.setTilt(45);

// Multiple Markers

{% for instance in queryset %}
var markers = [
// ['London Eye, London', 51.503454,-0.119562],
// ['Palace of Westminster, London', 51.499633,-0.124755],
// ['Ministry of Sound', 51.498231,-0.118468],
[{{ instance.place_id }}, {{ instance.place_lat }}, {{ instance.place_long }}]
];
{% endfor %}

// Info Window Content
var infoWindowContent = [
['<div class="info_content">' +
'<h3>London Eye</h3>' +
'<p>The London Eye is a giant...</p>' + '</div>'],
['<div class="info_content">' +
'<h3>Palace of Westminster</h3>' +
'<p>The Palace of Westminster is the...</p>' +
'</div>'],
['<div class="info_content">' +
'<h3>Ministry of Sound</h3>' +
'<p>Nice place.</p>' +
'</div>']
];

// Display multiple markers on a map
var infoWindow = new google.maps.InfoWindow(), marker, i;

// Loop through our array of markers & place each one on the map
for( i = 0; i < markers.length; i++ ) {
var position = new google.maps.LatLng(markers[i][1], markers[i][2], markers[i][3]);
bounds.extend(position);
marker = new google.maps.Marker({
position: position,
map: map,
title: markers[i][0]
});

// Allow each marker to have an info window
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infoWindow.setContent(infoWindowContent[i][0]);
infoWindow.open(map, marker);
}
})(marker, i));

// Automatically center the map fitting all markers on the screen
map.fitBounds(bounds);
}

// Override our map zoom level once our fitBounds function runs (Make sure it only runs once)
var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function(event) {
this.setZoom(14);
google.maps.event.removeListener(boundsListener);
});

}

</script>

{% endblock content %}

最佳答案

你应该为此使用 JSON。

context = {
"queryset": queryset,
"marker_list": json.dumps(marker_list)
}

在您的模板中,使用safe 过滤器,这样 Django 就不会转义符号:

 var markers = {{ marker_list|safe }}

关于javascript - 如何将 jQuery 变量设置为 django 模板变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34970090/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com