【发布时间】:2019-10-18 16:00:56
【问题描述】:
当我想将一个 dic 从views.py 传递给一个模板时,它没有正确呈现。
我尝试使用 |safe 和 JSON.parse(),但是两者都没有解决问题。 views.py 中似乎已经发生了错误。
views.py
participant_per_challenge = {}
for participant in challenge_participants:
if str(participant.challenge.id) in participant_per_challenge:
participant_per_challenge[str(participant.challenge.id)].append(participant.player.userid)
else:
participant_per_challenge[str(participant.challenge.id)] = []
participant_per_challenge[str(participant.challenge.id)].append(participant.player.userid)
my_dict = {
'challenges' : challenges,
'challenge_participants' : challenge_participants,
'unique_participants': unique_participants,
'participant_per_challenge': participant_per_challenge,
}
return render(request, "challengeview/index.html", context=my_dict)
这里是 views.py
的示例 dic{
"1": [
"bc5ac2b77a2d4b9e90ff4aa6012a4891",
"a61254636e5f432292459b406cf55f47"
],
"2": [
"a61254636e5f432292459b406cf55f47",
"bc5ac2b77a2d4b9e90ff4aa6012a4891"
]
}
index.html
<script type="text/javascript">
var player_per_challenge = "{{ participant_per_challenge|safe}}";
console.log(typeof player_per_challenge); //THIS RETURNS STRING
</script>
预期结果:我可以访问其参数的 JSON 对象
实际结果:一个字符串。
JSON.parse()效果不佳(“Uncaught SyntaxError: Unexpected token with JSON.parse”)。
【问题讨论】:
标签: javascript django django-templates django-views