Django 的模板语言(Django Template Language, 简称 **DTL**)
Django 的模板语言(Django Template Language, 简称 DTL)是一种简单而强大的工具,允许你在 HTML 中嵌入变量、控制结构(如条件判断、循环)、模板继承等逻辑。下面是一个系统化的入门讲解。
✅ 一、模板文件位置
默认推荐将模板放在项目根目录的 templates/ 文件夹下,例如:
myproject/
├── templates/
│ └── index.html
并在 settings.py 中设置模板路径:
TEMPLATES = [
{
...
'DIRS': [BASE_DIR / 'templates'],
...
},
]
✅ 二、模板基础语法
1. 变量输出
在模板中使用 {{ 变量名 }} 输出 Python 传递的变量值:
<h1>Hello, {{ username }}!</h1>
对应视图中:
def greet_view(request):
return render(request, 'index.html', {'username': 'Alice'})
2. 条件语句 {% if %}
{% if is_login %}
<p>Welcome back, {{ username }}!</p>
{% else %}
<p>Please log in.</p>
{% endif %}
3. 循环语句 {% for %}
<ul>
{% for item in item_list %}
<li>{{ forloop.counter }}. {{ item }}</li>
{% endfor %}
</ul>
内置的 forloop 提供循环状态,如:
forloop.counter:从 1 开始的索引forloop.first:是否为第一个元素
4. 过滤器(Filters)
过滤器用于对变量进行格式化,如:
{{ message|lower }} {# 小写输出 #}
{{ name|length }} {# 输出字符长度 #}
{{ created_at|date:"Y-m-d" }} {# 格式化日期 #}
5. 注释语法
{# 这是一个注释,模板渲染后不会出现 #}
✅ 三、模板继承
模板继承能帮助你构建统一的页面结构(如公共头部、导航栏等)。
1. 创建基础模板 base.html
<!-- templates/base.html -->
<html>
<head>
<title>{% block title %}我的网站{% endblock %}</title>
</head>
<body>
<div class="nav">导航栏</div>
<div class="content">
{% block content %}{% endblock %}
</div>
</body>
</html>
2. 子模板继承 index.html
{% extends "base.html" %}
{% block title %}首页{% endblock %}
{% block content %}
<h2>欢迎访问首页</h2>
<p>内容区域</p>
{% endblock %}
✅ 四、静态文件加载(配合模板使用)
- 引入静态文件模块:
{% load static %}
- 使用静态资源:
<link rel="stylesheet" href="{% static 'css/style.css' %}">
<img src="{% static 'images/logo.png' %}" alt="Logo">
确保在 settings.py 中配置了:
STATIC_URL = '/static/'
STATICFILES_DIRS = [BASE_DIR / 'static']
并将资源放在 static/ 目录下。
✅ 五、综合示例:完整的 HTML 模板
templates/index.html:
{% extends "base.html" %}
{% block title %}欢迎页{% endblock %}
{% block content %}
<h1>Hello, {{ username }}!</h1>
{% if hobbies %}
<ul>
{% for h in hobbies %}
<li>{{ h|capfirst }}</li>
{% endfor %}
</ul>
{% else %}
<p>你还没有填写兴趣爱好。</p>
{% endif %}
{% endblock %}
视图函数:
from django.shortcuts import render
def home_view(request):
context = {
'username': 'Tom',
'hobbies': ['reading', 'coding', 'running'],
}
return render(request, 'index.html', context)
✅ 六、模板调试技巧
-
使用
{% debug %}可以打印所有上下文变量(开发时用):{% debug %}

浙公网安备 33010602011771号