w8484855@qq.com 发表于 2017-9-3 23:23:48

Django 模板标签

本文和大家分享的主要是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:Lee 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 这是最后一次循环


来源:博客园
页: [1]
查看完整版本: Django 模板标签