admin管理员组文章数量:1424445
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
1 Answer
Reset to default 6{% for key, value in myDict.items %}
本文标签: javascriptHow do I iterate through a dictionary in Django TemplatesStack Overflow
版权声明:本文标题:javascript - How do I iterate through a dictionary in Django Templates? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745421474a2657918.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论