Reputation: 37
in my context there is a variable called "spots". I have a script where I print it in the document
<script >
var spotss = "{{ spots }}";
document.write(spotss)
</script>
The above code produces the following result:
[{u'rider_ability': u'Beginner, Intermediate, Expert', u'spot_distance': 2, u'water_type': u'Shallow, Chop, Small wave', u'water_quality': u'Clean', u'lat': 40.4026, u'lng': 14.9949, u'spot_name': u'Paestum'}, {u'rider_ability': u'Beginner, Intermediate, Expert', u'spot_distance': 2, u'water_type': u'Shallow, Chop, Small wave', u'water_quality': u'Clean', u'lat': 40.4271, u'lng': 14.9818, u'spot_name': u'Ponte di Ferro'}, {u'rider_ability': u'Beginner, Intermediate, Expert', u'spot_distance': 9, u'water_type': u'Shallow, Flat, Chop, Small wave', u'water_quality': u'Clean', u'lat': 40.343, u'lng': 14.9717, u'spot_name': u'Agropoli'}, {u'rider_ability': u'Beginner, Intermediate, Expert', u'spot_distance': 21, u'water_type': u'Chop, Small wave', u'water_quality': u'Clean', u'lat': 40.2315, u'lng': 14.9566, u'spot_name': u'Case del Conte'}, {u'rider_ability': u'Beginner, Intermediate, Expert', u'spot_distance': 26, u'water_type': u'Small wave', u'water_quality': u'Clean', u'lat': 40.1856, u'lng': 15.0239, u'spot_name': u'Acciaroli'}, {u'rider_ability': u'Intermediate, Expert', u'spot_distance': 28, u'water_type': u'Flat, Chop', u'water_quality': u'Crystal clear', u'lat': 40.1732, u'lng': 15.0846, u'spot_name': u'Pioppi'}, {u'rider_ability': u'Beginner, Intermediate, Expert', u'spot_distance': 31, u'water_type': u'Chop, Small wave', u'water_quality': u'Clean', u'lat': 40.1641, u'lng': 15.1423, u'spot_name': u'Marina di Casal Velino'}, {u'rider_ability': u'Expert', u'spot_distance': 35, u'water_type': u'Flat, Chop, Small wave', u'water_quality': u'Clean', u'lat': 40.6436, u'lng': 14.6984, u'spot_name': u'Cetara'}, {u'rider_ability': u'Intermediate, Expert', u'spot_distance': 35, u'water_type': u'Shallow, Flat, Chop, Small wave', u'water_quality': u'Clean', u'lat': 40.6775, u'lng': 14.7587, u'spot_name': u'Salerno'}, {u'rider_ability': u'Intermediate, Expert', u'spot_distance': 42, u'water_type': u'Chop, Small wave', u'water_quality': u'Crystal clear', u'lat': 40.6262, u'lng': 14.5883, u'spot_name': u'Spiaggia Duoglie'}]
Which is a list of dictionaries, probably as a "string".
Now my need is to iterate over this list of dictionaries into another script on the same html, and I also need to access dictionaries values while looping. How can I do?
Upvotes: 1
Views: 205
Reputation: 6822
Use Django's safe filter :
<script >
var spotss = "{{ spots | safe}}";
document.write(spotss);
</script>
Or you may need:
<script >
var spotsArray = {{ spots | safe}};
spotsArray.forEach(function(spot) {
console.log(spot)
});
</script>
spotsArray
contains a list of objects, you can iterate through that list with forEach
Upvotes: 2