设置一个全局字段:
USER_DICT = {
'k1': 'root1',
'k2': 'root2',
'k3': 'root3',
}
def index(request):
return render(request, 'test.html', {'user_dict': USER_DICT})#将字典传回前端
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{{ user_dict.k1 }} #直接通过键来取值
<ul>
{% for k, v in user_dict.items %} #通过迭代取键和值
<li>{{ k }}----{{ v }}</li>
{% endfor %}
</ul>
<ul>
{% for k in user_dict.keys %} #通过迭代取键
<li>{{ k }}</li>
{% endfor %}
</ul>
<ul>
{% for v in user_dict.values %} #通过迭代取值
<li>{{ v }}</li>
{% endfor %}
</ul>
</body>
</html>
输出结果: