Lord Elrond
Lord Elrond

Reputation: 16032

How do I iterate through a dictionary in Django Templates?

I am trying to iterate through a dictionary in my django template and save the values to window.obj, but it is not working.

views.py:

def myView(req):
...
myDict = {'foo':"[1,2]", 'bar':"[3,4]"} 

return render(req, 'myPage.html', {'myDict':myDict})

myPage.html:

<script type="text/javascript">
window.obj = {}
window.obj["foo"] = "{{ myDict.foo }}";

{% for key, value in myDict %}

window.obj["{{ key }}"] = "{{ value }}";

{% endfor %}
</script>

...

<script> 
console.log(window.obj.foo); //prints {foo: "[1,2]"} 
console.log(window.obj.bar); //prints undefined
</script>

Note: I can't use myDict.foo on my actual project

What am I missing here?

Upvotes: 0

Views: 4027

Answers (1)

bertucho
bertucho

Reputation: 726

{% for key, value in myDict.items %} 

Upvotes: 6

Related Questions