javascript - How do I iterate through a dictionary in Django Templates? - Stack Overflow

I am trying to iterate through a dictionary in my django template and save the values to window.obj, bu

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?

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?

Share Improve this question edited Feb 20, 2019 at 21:56 Lord Elrond asked Feb 20, 2019 at 21:45 Lord ElrondLord Elrond 16.1k8 gold badges54 silver badges91 bronze badges 1
  • Try using dict.items instead {% for key, value in myDict.items %} – Håken Lid Commented Feb 20, 2019 at 21:54
Add a ment  | 

1 Answer 1

Reset to default 6
{% for key, value in myDict.items %} 

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745421474a4626982.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信