我想避免在我的页面加载到客户端后进行ajax调用以获取我需要的数据。所以我想将这些数据与模板一起发送。
我可以将它以json格式放在我的html页面中的标签的data- * attributs中,但有没有一种干净的方法可以做到这一点?
我想要的是做这两件事的事情:
return HttpResponse(json.dumps({'obj':'val'}), mimetype="application/json")
和
return render(request, 'index.html', context)
答案 0 :(得分:2)
不确定。尝试:
import json
template_context = {
'my_json': json.dumps(json_object)
}
return render_template('index.html', **template_context )
在模板中:
<script>
myJSON = {{ my_json|safe }};
</script>