1、什么是模板
模板是一个文本,用于分离文档和表现内容,通常用于生成HTML。
<html>
<head>template</head>
<body>
<p>Hello{{name}}</p>
<ul>
{% for item in itemlist %}
<li>{{item}}</li>
{% endfor %}
</ul>
{% if status %}
<p> I love python </p>
{% else %}
<p> I love django </p>
{% endif %}
</body>
2、怎么使用模板?
(1)可以用原始的模板代码字符串创建一个template对象。
(2)调用模板对象的render()方法,并且传入一套变量的context
python manage.py shell
from django import template
t = template.Template('hello,{{name}}')
c = template.Context({'name':'django'})
print t.render(c)
一旦你创建了一个template对象,你就可以用context处理器来传递数据给它,最用调用render()方法来渲染它。
3、模板中过滤器
过滤器就是将模板中的变量过滤一遍,在变量显示前修改它的一个方法。
如:下列代码中,upper就是一个过滤器:将name这个变量转化为全部为大写字母的格式。
{{name|upper}}
4、模板的加载
(1)首先在应用中创建一个文件夹templates用于存放模板,
<html>
<head>mytemplate</head>
<body>
<p>Hello {{name}}</p>
</body>
</html>
(2)修改setting.py
import os
TEMPLATE_DIR=os.path.join(os.path.dirname(__file__),'templates')
(3)在python shell中验证
from django.template.loader import get_template
t = get_template("1.html")
t
from django.shortcuts import render_to_response
def views(request):
return render_to_response('1.html',{"name":"hello"})
除此之外,django还给模板提供了继承功能。如让2.html继承1.html
1.html
<html>
<head>1.html</head>
<body>
{% block content %}
<p>Hello world</p>
{% endblock %}
</body>
</html>
2.html
{% extends '1.html' %}
{% block content %}
{% endblock %}
写一个视图函数验证一下
views.py
from django.shortcuts import render_to_response
def views(request):
return render_to_response('2.html')
urls.py
(r'^hello/$',views)
启动应用,在浏览器输入localhost:8000/views