在Django框架中,模板是可以帮助开发者快速生成呈现给用户页面的工具 。
模板的设计方式实现了我们MVT重VT的解耦,VT有着N:M的关系,一个V可以调用任意T,一个T可以供任意V使用。 模板处理分为两个过程: 加载和渲染。
创建模板
创建与应用和项目同级的模板文件夹,并修改项目中的配置文件使其生效。
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(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',
],
},
},
]
'DIRS': [os.path.join(BASE_DIR,'templates')],
模板所在目录
修改配置文件
模板语法及相关例子
注释
注释可见,可运行
<!-- 注释内容 -->
单行注释注释不可见,不可运行
单行注释(页面源码中不会显示注释内容)
{# 被注释掉的内容 #}
多行注释注释不可见,不可运行
{% comment %}
{% endcomment %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
{% load static %}
<!--<link rel="stylesheet" href="/static/css/index.css">-->
<link rel="stylesheet" href="{% static 'css/index.css' %}">
</head>
<body>
<h2>你好</h2>
<table>
<thead>
<th>序号</th>
<th>id</th>
<th>name</th>
<th>age</th>
</thead>
<tbody>
{% for stu in students %}
<tr>
<td>{{ forloop.counter }}</td>
<td>{{ stu.id}}</td>
{# <td {% if stu.id == 3 %} style="color:red;"{% endif %}>{{ stu.s_name}}</td> #}
<td {% if forloop.first %} style="color:red;"{% endif %}>{{ stu.s_name}}</td>
<td {% if forloop.last %} style="color:yellow;"{% endif %}>{{ stu.s_age}}</td>
</tr>
{% endfor %}
</tbody>
</table>
<!--<!–解析变量–>-->
<!--{% for stu in students %}-->
<!--<table>{{ stu.s_name }}</table>-->
<!--{% endfor %}-->
</body>
</html>
运行结果
模板继承
挖坑
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>
{% block title %}
{% endblock %}
</title>
{% block extCss %}
{% endblock %}
{% block extJs %}
{% endblock %}
</head>
<body>
{% block content %}
{% endblock %}
</body>
</html>
填坑
{% extends 'base.html' %}
{% block title %}
注册
{% endblock%}
{% block content %}
<form action="" method="post">
{{ form.errors.username }}
<p>用 户 名:<input type="text" name="username"></p>
{{ form.errors.password }}
<p>密 码:<input type="password" name="password"></p>
{{ form.errors.password2 }}
<p>确认密码:<input type="password" name="password2"></p>
<input type="submit" value="提交">
</form>
{% endblock%}