本文和大家分享的主要是django
中模板标签相关内容,一起来看看吧,希望对大家
学习django有所帮助。
1.IF标签
Hello World/views.py
1
from django.shortcuts
import render
2
3
class
Person(object):
4
def
__init__(self,name,age,sex):
5 self.name=name
6 self.age=age
7 self.sex=sex
8
9
def
say(self):
10
return "I'm %s." %self.name
11
12
def
index(request):
13 #
传入普通变量
14 #
传入数据为
html
中的变量:
views
中的变量
15 #return render(request,'index.html',{'title':'Welcome','name':'KeinLee'})
16
17 #
传入字典变量
18 person = {'name':'Lee','age':20,'sex':'male'}
19 #
传入列表变量
20 book_list =['Python','Java','C']
21 #book_list =[]
22 #
传入对象变量
23 #person=Person('Lucky',18,'female')
24
return render(request,'index.html',{'title':'Welcome','person':person,'book_list':book_list})
views.py
(1
)
if ...elif...else...endif
Hello World/temlplates/index.html
{%
if book_list.0 == 'Java' %}
第一本书是Java{%
elif book_list.0 == 'Python' %}
第一本书是Python{%
else %}
第一本书是C{%
endif %}
View Code
结果为:第一本书是Python
(2
)
if...and...or...not...endif
注意:and
和
or
可以同用,但是
and
的优先级比
or
高
Hello World/temlplates/index.html
{%
if book_list or person %}
存在book_list
或者
person{%
endif %}
{%
if book_list and person %}
book_list
和
person
都存在
{%
endif %}
{%
if book_list and not person %}
存在book_list
不存在
person{%
endif %}
View Code
结果为:存在book_list
或者
person
、
book_list
和
person
都存在、(空)
(3
)
if
符号运算(
==
、
!=
、
>
、
>=
、
<=
、
<
、
in
、
not in
、
is
、
is not
)
if is XX True
这个是当且仅当
XX
为真,这个暂时理解不了
{%
if book_list.0 == 'Python' %}
1.
第一本书是
Python{%
endif %}
{%
if book_list.0 != 'Python' %}
2.
第一本书不是
Python{%
endif %}
{%
if person.age <= 20 %}
3.
这个人的年龄没超过
20{%
else %}
4.
这个人的年龄超过
20{%
endif %}
{%
if 'Python'
in book_list %}
5.Python
在
book_list
列表里
{%
endif %}
{%
if 'Py' not
in book_list %}
6.Py
在
book_list
列表里
{%
endif %}
{%
if book_list.4 is not True %}
7.book_list.4
不存在
{%
endif %}
{%
if book_list is not None%}
8.book_list
列表存在
{%
endif %}
View Code
结果:1
、
3
、
5
、
6
、
7
、
8
能够显示
2.For标签
(1
)列表
for
循环
{%
for book
in book_list %}{{book}}{%
endfor %}
结果:Python Java C
(2
)字典
for
循环
{%
for k,v
in person.items %}{{k}}:{{v}}{%
endfor %}
结果:sex:male name

ee age:20
(3
)
for...empty
(在
views.py
中没有定义
book_list2
)
{%
for book
in book_list2 %}{{book}}{%
empty %}
没有这个列表或者该列表为空{%
endfor %}
结果:没有这个列表或者该列表为空
(4
)
forloop
forloop.counter
循环记数,默认
1
开始
forloop.counter0
循环记数,从
0
开始
forloop.revcounter
循环到记数,默认
1
结束
forloop.revcounter0
循环记数,到
0
结束
forloop.first
第一次循环
bool
值为
True
,一般与
if
连用
forloop.last
最后一次循环
bool
值为
True
,一般与
if
连用
forloop.parentloop
循环嵌套中对上一层循环的操作
{%
for k
in person %}{%
if forloop.first %}
这是第一次循环{%
elif forloop.last%}
这是最后一次循环{%
else %}{{k}}{%
endif %}{%
endfor %}
结果:这是第一次循环 name
这是最后一次循环
来源:
博客园