Django模版进阶

# -*- coding: utf-8 -*-
from django.shortcuts import render
def home(request):
 string = "测试"
 return render(request, 'index.html', {'string': string})

我们在函数当中把字符串名称为string到index.html文件,在模版中这样使用

index.html

{{ string }}

for循环和list内容的显示

def home(request):
 TutorialList = ["HTML", "CSS", "jQuery", "Python", "Django"]
 return render(request, 'index.html', {'TutorialList': TutorialList})

在模版中这样使用

index.html

学习列表:

{% for i in TutorialList %}
{{ i }}
{% endfor %}

for循环要有一个结束标记:{% endfor %}

简单总结一下:一般变量之类的用{{ 变量 }},功能类的比如循环,判断用{% 标签 %}

显示字典的内容:

def home(request):
 info_dict = {'site': '测试', 'content': '测试内容'}
 return render(request, 'home.html', {'info_dict': info_dict})

模版引用:

站点:{{ info_dict.site }} 内容:{{ info_dict.content }}

还可以遍历字典

{% for key, value in info_dict.items %}
{{ key }}: {{ value }}
{% endfor %}

在模版中进行条件判断和for循环详细操作:

def home(request):
 List = map(str, range(100))
 return render(request, 'index.html', {'List': List})

引用

index.html

{% for item in List %}
{{ item }},
{% endfor %}

{% for item in List %}
{{ item }}{% if not forloop.last%},{% endif %}
{% endfor %}

在for循环当中有很多有用的东西,如下:

forloop.counter 索引从 1 开始算
forloop.counter0 索引从 0 开始算
forloop.revcounter 索引从最大长度到 1
forloop.revcounter0 索引从最大长度到 0
forloop.first 当遍历的元素为第一项时为真
forloop.last 当遍历的元素为最后一项时为真
forloop.parentloop
用在嵌套的 for 循环中,
获取上一层 for 循环的 forloop

当列表中可能为空用for empty

{% for athlete in athlete_list %}
<li>{{ athlete.name }}</li>
{% empty %}
<li>抱歉,列表为空</li>
{% endfor %}

原文地址:https://www.cnblogs.com/chaoe/p/5983992.html