1. 取字符串的值
返回模板的時候,加上傳入的字符串:
def index(request):
return render(request, 'index/index.html', {'username': 'thanlon'})
模板中解析傳入的字符串:
{{ username }}
2. 取列表的值
返回模板的時候,加上傳入列表:
def index(request):
return render(request, 'index/index.html', {'username': ['thanlon','Kiku']})
模板中解析傳入的列表,直接通過索引取:
{{ username.0 }}
{{ username.1 }}
通過循環遍歷:
{% for item in username %}
{{ item }}
{% endfor %}
3. 取字典的值
返回模板的時候,加上傳入字典:
def index(request):
return render(request, 'index/index.html', {
'user_dict': {'name': 'thanlon', 'age': 23}
})
模板中解析傳入的字典:
{{ user_dict.name }}
{{ user_dict.age }}
4. 取嵌套在列表中的字典的值
返回模板的時候,加上傳入嵌套在列表中的字典:
def index(request):
return render(request, 'index/index.html', {
'user_list_dict': [
{'id': 1, 'name': 'thanlon'},
{'id': 2, 'name': 'kuku'},
]
})
模板中解析傳入的嵌套在列表中的字典,通過索引取值:
{{ user_list_dict.0.id}}
{{ user_list_dict.0.name}}
{{ user_list_dict.1.id}}
{{ user_list_dict.0.name}}
模板中解析傳入的嵌套在列表中的字典,通過通過循環取值:
{% for row in user_list_dict %}
{{ row.id }}
{{ row.name }}
{% endfor %}