基础
- {{ person_name }} 变量
- {% if ordered_warranty %} 模板标签(template tag) : 仅通知模板系统完成某些工作的标签。比如if标签for标签
- {{ship_date|date:”F j, Y” }} filter过滤器
将变量ship_date传递给date过滤器,同时指定参数”F j,Y”。date过滤器根据参数进行格式输出。 过滤器是用管道符(|)来调用的
模板细节
首先,模板Template与上下文Context对象结合时,使用了render函数
t = Template('My name is {{ name }}.')
c = Context({'name': 'Stephane'})
t.render(c)
render函数的返回值是unicode对象,而不是字符串对象。实际上在Django框架中一直使用unicode对象而不是字符串。
模板中使用列表调用方式:
{{ items.2}} #items = [1,2,3]
但是不能使用负数列表索引,比如
{{ items.-1}}
在使用标签或变量时,最好有if语句检测其是否为空的好习惯
关于if-else标签
- if标签不允许在同一个标签中使用and和or
- 没有elif标签,可以通过嵌套的if标签来实现
- 每一个if-else都要用endif标签关闭(for标签亦是如此)
以上条目都是为了if标签逻辑性不造成混乱
for标签
- 使用endfor标签来关闭
- 为防止for循环的列表对象为空,特别有一个empty标签,通过它我们可以定义当列表为空时的输出内容
forloop.counter
{% for item in todo_list %}
<p>{{ forloop.counter }}: {{ item }}</p>
{% endfor %}
这个计数器是从1 开始的。forloop.counter0类似于forloop.counter,只不过它是从0计数
forloop.revcounter与forloop.revcounter0
这两个变量与counter,counter0正好相反,每次循环减1
forloop.first
在第一次循环时,这个变量的值为True。
forloop.last
在执行最后一次循环的时候,这个变量的值为True
forloop.parentloop
这个变量指向当前循环的上一级循环对象
Context和forloop变量
- ifequal/ifnotequal
判断相等/不等,最后需要用endifequal结束
{% ifequal section 'sitenews' %}
<h1>Site News</h1>
{% else %}
<h1>No News Here</h1>
{% endifequal %}
但是只能判断数字和字符串,其他类型不能使用
注释
{# this is a comment #}
过滤器
{{ my_list|first|upper }}
这句代码的意思:先找出my_list的第一个元素,并且大写
模板的使用
render_to_response
使用render_to_response(‘html文件dir’,{映射字典})的方式来节省代码量
def current_datetime(request): now = datetime.datetime.now()
return render_to_response('current_datetime.html', {'current_date': now})
locals()
对于当前模块的应用-对象关系,local()函数可以直接将这些关系包装成为映射字典对象,从而使代码更加简单:
def current_datetime(request):
current_date = datetime.datetime.now()
return render_to_response('current_datetime.html', locals())
这样我们不需要手动设置context字典,但是模块中的变量名一定要对应字典的键值
模板的继承
header.html
将头部html放在头部文件中
footer.html
将底部html放在footer.html中
基础模板
使用{% block content %}标签来标明可以替换重载的部分
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="en">
<head>
<title>{% block title %}{% endblock %}</title>
</head>
<body>
<h1>My helpful timestamp site</h1>
{% block content %}{% endblock %}
{% block footer %}
<hr>
<p>Thanks for visiting my site.</p>
{% endblock %}
</body>
</html>
子模板
通过{% extends “dir” %}来标明继承自基础模板,然后在重载部分使用{% block title %}…{% endblock %}来重载
{% extends "base.html" %}
{% block title %}The current time{% endblock %}
{% block content %}
<p>It is now {{ current_date }}.</p>
{% endblock %}