如何将jQuery变量设置为django模板变量 [英] How to set jQuery variable as a django template variable

查看:77
本文介绍了如何将jQuery变量设置为django模板变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using a jQuery script inside of a Django template in order to render a Google Map. The goal is to plot multiple markers on the map. I've tried two things:


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

  1. Set the jQuery var to a Django template variable, which I defined as a list in views.py. Was not able to produce any markers in this case. Just a blank map.

var markers = {{marker_list}};

var markers = {{ marker_list }};

我在页面上打印了marker_list确认,这是我上次测试中的一个:marker_list = [['Chiang Mai Park',21.0333,21.0333],['胡志明陵墓',21.036666667,21.036666667]]

I printed marker_list on the page to confirm, which was this in my last test: marker_list = [['Chiang Mai Park', 21.0333, 21.0333], ['Ho Chi Minh Mausoleum', 21.036666667, 21.036666667]]

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

Make a for loop with template tags inside the jQuery script, and build the list with template variables. With this, only one marker will plot, even if there are multiple locations in the list (see marker_list above).

{%例如在queryset%}}

{% for instance in queryset %}

var markers = [
[{{instance.place_id}},{{instance.place_lat}},{{instance.place_long}}]
] ;

var markers = [ [{{ instance.place_id }}, {{ instance.place_lat }}, {{ instance.place_long }}] ];

{%endfor%}

{% endfor %}

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

Full code is below showing attempt #2. Note that "var markers" in the javascript requires a list of a lists. i.e. var markers = [[name1, latitude1, longitude1], [name2, latitude2, longitude2]].

任何帮助都将非常感谢。我是Django和Javascript n00b。

Any help would be much appreciated. I'm both a Django and 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不会转义符号:

and in your template, use the safe filter so Django doesn't escape the symbols:

 var markers = {{ marker_list|safe }}

这篇关于如何将jQuery变量设置为django模板变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆