How To Set Jquery Variable As A Django Template Variable
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: Set the jQuery var t
Solution 1:
You should use JSON for this.
context = {
"queryset": queryset,
"marker_list": json.dumps(marker_list)
}
and in your template, use the safe
filter so Django doesn't escape the symbols:
var markers = {{ marker_list|safe }}
Solution 2:
By doing {{ marker_list }}
you just end up with a string which is obviously no good, the solution I normally go with is to define a blank array and then append to it
var markers = [];
{% for instance in queryset %}
markers.append([{{ instance.place_id }}, {{ instance.place_lat }}, {{ instance.place_long }}]);
{% endfor %}
Of course you could just close the array after the for loop, this can produce a jslint error although it should work just as well.
var markers = [
{% for instance in queryset %}
[{{ instance.place_id }}, {{ instance.place_lat }}, {{ instance.place_long }}],
{% endfor %}
];
Post a Comment for "How To Set Jquery Variable As A Django Template Variable"