使用模板变量:
在html文件中,{{title}}即为模板变量,
在view.py文件中,render函数,增加第三个参数,以字典形式给值。
def index(req): return render(req, 'index1.html', {'title': 'mypage', 'user': 'tom'})
可以将‘mypage’,‘tom’改成变量,实现接口和动态;
该变量可以是基本变量(单值)、字典、list、类等,在html中可以索引{{user.key}}
字典
def index(req): user = {'name':'tom', 'age':23, 'sex':'male'} return render(req, 'index1.html', {'title': 'mypage', 'user': user})
对象
(可以使用的对象属性、方法),在调用对象的方法时,注意没有参数,要有return
def index(req): user = Person('tom', 24, 'male') return render(req, 'index1.html', {'title': 'mypage', 'user': user})
在html中存在优先级:先基本变量,再字典、对象的属性、对象的方法、最后列表
模板标签的使用:
{% if xx%}
{% else %}
{% endif %}
判断条件xx:
- 可以是变量,判断变量是否存在
- 可以是boolean操作, 使用and、or、not;注意不能使用();django1.3不可以and和or连用,django1.11可以
- 可以是关系运算,等于,不等于,大小,大于等于等,注意:必须要有空格隔开!
- 可以是in、not in运算
{% for book in book_list %}
<li>book</li>
{% empty %} #可以没有这句
book_list为空
{% endfor %}
- 被遍历对象可以是llist
- 对字典遍历,跟python对dict遍历一样,for u in user得到键的遍历,for k, v in user.items: {{k}} {{v}}
- 可以是复合数据类型
forloop.counter |
序号,从1开始 |
forloop.counter0 |
从0开始 |
forloop.revcounter |
反向 |
forloop.revcounter0 |
反向 |
forloop.first |
True if the firsh through the loop |
forloop.last | |
forloop.parentloop |
for nested loops, this is the loop 'above' the current one |
- for ... empty
使用模板:
#from django.shortcuts import render 1 #coding:utf-8 2 #from django.shortcuts import render 3 from django.template import loader, Context, Template 4 from django.http import HttpResponse 5 6 # Create your views here. 7 def index(seq): 8 t = loader.get_template('index.html') #加载模板,用文件 9 c = Context({'uname': 'alen'}) #生成Context对象 10 html = t.render(c) #渲染 11 return HttpResponse(html) #输出,我的测试报错!没找到问题 12 13 def index1(req): 14 t = Template('<h1>hello {{uname}}</h1>') #用字符串,生成模板对象 15 c = Context({'uname':'csvt'}) 16 html = t.render(c) #渲染 17 return HttpResponse(html) #输出,测试成功
以上两种方法,被简化为使用render方法
1.3使用的是from django.shortcuts import render_to_response