前言
在view.py里写html代码终究是不友好的。极好的方法是符合MVC设计思想,将模板分离出来,并且希望模板里面能输出变量。
简单的例子
模板文件夹
视图文件夹是分为模板文件
和静态文件
,模板文件一般内嵌第三发给语法的html代码,静态文件诸如css,js,jpg文件。
在learn_django目录下建立templates文件夹,并建立hello.html,目录结构:
learn_django/
|-- learn_django
| |-- __init__.py
| |-- __init__.pyc
| |-- settings.py
| |-- settings.pyc
| |-- urls.py
| |-- urls.pyc
| |-- view.py
| |-- view.pyc
| |-- wsgi.py
| `-- wsgi.pyc
|-- manage.py
`-- templates
`-- hello.html
hello.html代码如下:
<h1>{{ hello }}</h1>
注:模板中变量使用两个大括号。
配置模板路径
修改learn_django/setting.py
找到TEMPLATES
中的DIRS:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BASE_DIR+"/templates",],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
修改view.py
# -*- coding: utf-8 -*-
#from django.http import HttpResponse
from django.shortcuts import render
def hello(request):
context = {}
context['hello'] = 'Hello World!'
return render(request, 'hello.html', context)
为了在模板使用变量,需要一个字典作为参数。 访问页面就可以看到:
这样就简单实现了数据与视图分离。
Django 模板标签
if else 标签
基本语法格式如下:
{% if condition1 %}
... display 1
{% elif condiiton2 %}
... display 2
{% else %}
... display 3
{% endif %}
if/else
支持嵌套,标签接受and or not
关键字进行判断。
for 标签
{% for %}
允许我们在一个序列上迭代,与Python的for语法一直,都是用for X in Y
的形式:
<ul>
{% for item in article_list %}
<li>{{ item.name }}</li>
{% empty %}
<li>抱歉,列表为空</li>
{% endfor %}
</ul>
给标签增加一个 reversed 使得该列表被反向迭代:
{% for item in article_list reversed %}
//code...
{% endfor %}
{% for %}
标签一样支持嵌套。
ifequal/ifnotequal 标签
{% ifequal %}
标签比较两个值,当他们相等时,显示在 {% ifequal %} 和 {% endifequal %} 之中所有的值。
下面的例子比较两个模板变量 user 和 currentuser :
{% ifequal user currentuser %}
<h1>Welcome!</h1>
{% else %}
<h1>No equal</h1>
{% endifequal %}
注释标签
{# 这是一个注释 #}
过滤器
模板过滤器可以在变量被显示前被修改,过滤器是否管道符号,如:
{{ name|lower }}
//多个管道
{{ my_list|first|upper }}
//有的过滤器需要参数,参数后面总是用引号包含
{{ bio|truncatewords:"30" }}
include 标签
{% include %}
标签允许在模板中包含其它的模板的内容。
下面这两个例子都包含了 nav.html 模板:
{% include "nav.html" %}
模板继承
模板可以用继承的方式来实现复用。 接下来我们先创建之前项目的 templates 目录中添加 base.html 文件,代码如下:
<html>
<head>
<title>Hello World!</title>
</head>
<body>
<h1>Hello World!</h1>
{% block mainbody %}
<p>original</p>
{% endblock %}
</body>
</html
以上代码中,名为mainbody的block
标签是可以被继承者们替换掉的部分。
所有的 {% block %} 标签告诉模板引擎,子模板可以重载这些部分。
hello.html中继承base.html,并替换特定block,hello.html修改后的代码如下:
{% extends "base.html" %}
{% block mainbody %}
<p>继承了 base.html 文件</p>
{% endblock %}