今天是二零一伍年九月十六日。
1、把一个字符串通过模板的方式展现在网页上,我们可以这样编写我们的views.py:
from django.shortcuts import render
# Create your views here.
def home(request):
string = u"我是strange"
return render(request , 'home.html' , {'string' : string})
然后我们在我们的模板部分可以改写成:
<!DOCTYPE html>
<html>
<head>
<title>欢迎光临</title>
</head>
<body>
{{string}}
</body>
</html>
然后运行服务器,我们就可以得到我们的字符串了。
2、然后我们可以尝试在模板中加入一个循环,这样可以遍历出我们list中的所有元素。首先我们的views.py里的视图函数要return这样一个List变量。
from django.shortcuts import render
# Create your views here.
def home(request):
NameList = ["strange" , "jane" , "jack" ]
return render(request , 'home.html' , {'NameList' : NameList})
然后我们在模板函数里面要尝试写出遍历:
<!DOCTYPE html>
<html>
<head>
<title>欢迎光临</title>
</head>
<body>
{% for i in NameList %}
{{ i }}
{% endfor %}
</body>
</html>
3、想要传输一个字典并且打印出来也是可以的,常理,我们还是要传输一个dict给模板:
from django.shortcuts import render
# Create your views here.
def home(request):
SexDict = {'strange' : '男' , 'jane' : '女' , 'jack' : '男' }
return render(request , 'home.html' , {'SexDict' : SexDict})
然后我们在模板里:
<!DOCTYPE html>
<html>
<head>
<title>欢迎光临</title>
</head>
<body>
{{ SexDict.strange }}
</body>
</html>
当然我们还可以用一个循环遍历我们的dict:
<!DOCTYPE html>
<html>
<head>
<title>欢迎光临</title>
</head>
<body>
{% for key , value in SexDict.items %}
{{key}}: {{value}}
{%endfor%}
</body>
</html>
5、当然,我们还可以在我们的模板中写出一个判断语句:
<!DOCTYPE html>
<html>
<head>
<title>欢迎光临</title>
</head>
<body>
{% for value in List %}
{{ value }}{% if not forloop.last %},{% endif %}
{% endfor %}
</body>
</html>
其中我们使用到的forloop.last是我们的一个自带变量,当我们遍历到最后一个元素的时候,他的值就为真,如果不是就为反。除了forloop.last以外,我们用到很多其他的遍历变量:
变量名 描述
forloop.counter 索引从 1 开始算
forloop.counter0 索引从 0 开始算
forloop.revcounter 索引从最大长度到 1
forloop.revcounter0 索引从最大长度到 0
forloop.first 当遍历的元素为第一项时为真
forloop.last 当遍历的元素为最后一项时为真
forloop.parentloop 用在嵌套的 for 循环中,获取上一层 for 循环的 forloop
比如我们尝试使用forloop.first:
<!DOCTYPE html>
<html>
<head>
<title>欢迎光临</title>
</head>
<body>
{% for value in List %}
{% if not forloop.first %}->{% endif %}
{{ value }}
{% endfor %}
</body>
</html>
6、在模板里也可以使用一些逻辑语句,配合上我们的if句柄,可以做很多组合:
{% if var >= 90 %}
{% elif var >= 80 %}
{% elif var >= 70 %}
{% elif var >= 60 %}
{% else %}
{% endif %}
而上述语句中使用的var就是我们在视图函数里传入的参数。除了简单的逻辑符号,and, or, not, in, not in 也可以在模板中使用。in和not in的使用方法我想已经不用介绍。