Django模板基础
Django模板基础[编辑 | 编辑源代码]
Django模板系统是Django框架中用于生成动态HTML的核心组件。它允许开发者将Python逻辑与HTML结构分离,遵循MVC(模型-视图-控制器)设计模式中的视图层实现。本文将从基础语法到实际应用全面讲解Django模板系统的核心功能。
模板系统概述[编辑 | 编辑源代码]
Django模板是一个文本文件(通常是HTML),包含两种特殊内容:
- 变量:用双大括号包裹(
模板:Variable
) - 标签:用大括号和百分号包裹(
{% tag %}
)
模板系统通过上下文处理器将Python变量转换为HTML输出,同时提供控制流、过滤器和模板继承等高级功能。
基本示例[编辑 | 编辑源代码]
<!-- templates/welcome.html -->
<!DOCTYPE html>
<html>
<head>
<title>{{ title }}</title>
</head>
<body>
<h1>Welcome, {{ user.username }}!</h1>
{% if user.is_authenticated %}
<p>You have {{ notifications.count }} new notifications.</p>
{% else %}
<p>Please <a href="/login">log in</a>.</p>
{% endif %}
</body>
</html>
对应的视图函数:
from django.shortcuts import render
def welcome_view(request):
context = {
'title': 'User Dashboard',
'user': request.user,
'notifications': request.user.notifications.unread()
}
return render(request, 'welcome.html', context)
核心功能详解[编辑 | 编辑源代码]
变量输出[编辑 | 编辑源代码]
变量通过{{ }}
语法输出,Django会尝试以下查找顺序:
1. 字典查找(my_dict.key
)
2. 属性查找(my_object.attribute
)
3. 方法调用(不带参数的方法)
4. 列表索引(my_list.0
)
过滤器[编辑 | 编辑源代码]
过滤器通过管道符(|
)对变量进行转换:
<p>{{ publish_date|date:"Y-m-d" }}</p> <!-- 输出:2023-07-15 -->
<p>{{ text|truncatechars:50 }}</p> <!-- 截断至50字符 -->
<p>{{ value|default:"N/A" }}</p> <!-- 默认值 -->
常用内置过滤器:
length
:返回列表长度lower
/upper
:大小写转换join
:列表连接为字符串safe
:标记字符串为安全HTML
控制流标签[编辑 | 编辑源代码]
条件判断[编辑 | 编辑源代码]
{% if temperature > 30 %}
<p>Hot weather</p>
{% elif temperature > 20 %}
<p>Pleasant weather</p>
{% else %}
<p>Cold weather</p>
{% endif %}
循环[编辑 | 编辑源代码]
<ul>
{% for item in item_list %}
<li>{{ forloop.counter }}. {{ item.name }}</li>
{% empty %} <!-- 当列表为空时显示 -->
<li>No items available</li>
{% endfor %}
</ul>
循环变量:
forloop.counter
:当前迭代次数(从1开始)forloop.counter0
:从0开始的索引forloop.revcounter
:剩余迭代次数
模板继承[编辑 | 编辑源代码]
Django模板系统支持类似面向对象的继承机制:
基础模板(base.html
):
<!DOCTYPE html>
<html>
<head>
<title>{% block title %}Default Title{% endblock %}</title>
</head>
<body>
<div id="content">
{% block content %}{% endblock %}
</div>
</body>
</html>
子模板(child.html
):
{% extends "base.html" %}
{% block title %}Custom Title{% endblock %}
{% block content %}
<h1>Main Content</h1>
{% include "partials/navbar.html" %}
{% endblock %}
高级特性[编辑 | 编辑源代码]
自定义过滤器[编辑 | 编辑源代码]
创建自定义过滤器(myapp/templatetags/custom_filters.py
):
from django import template
register = template.Library()
@register.filter(name='multiply')
def multiply(value, arg):
return float(value) * float(arg)
使用示例:
{% load custom_filters %}
<p>Total: {{ price|multiply:quantity }}</p>
模板上下文处理器[编辑 | 编辑源代码]
上下文处理器允许自动向所有模板添加变量。示例处理器:
# myapp/context_processors.py
def site_settings(request):
return {
'SITE_NAME': 'My Django Site',
'CURRENT_YEAR': datetime.now().year
}
在settings.py
中注册:
TEMPLATES = [
{
'OPTIONS': {
'context_processors': [
# ...
'myapp.context_processors.site_settings',
],
},
},
]
最佳实践[编辑 | 编辑源代码]
1. 保持模板简单:将复杂逻辑移入视图或自定义标签
2. 合理使用继承:创建3-4层继承结构(base → section → page)
3. 缓存常用片段:使用{% cache %}
标签缓存静态部分
4. 安全考虑:始终对用户输入使用escape
过滤器(默认启用)
性能优化[编辑 | 编辑源代码]
Django模板经过高度优化,但以下技巧可提升性能:
- 使用
{% with %}
缓存复杂查询结果 - 避免在循环中进行数据库查询
- 使用
select_related
或prefetch_related
减少查询次数
数学公式支持[编辑 | 编辑源代码]
Django模板可以与数学公式结合使用,例如显示计算结果:
在模板中显示动态生成的公式:
{% with result=value|multiply:constant %}
<p>计算结果:<math>{{ result }} = {{ value }} \times {{ constant }}</math></p>
{% endwith %}
总结[编辑 | 编辑源代码]
Django模板系统提供了强大的工具来分离业务逻辑和展示层。通过掌握变量输出、过滤器、控制流和模板继承等核心概念,开发者可以创建可维护的动态网页。高级用户还可以通过自定义过滤器和上下文处理器扩展模板功能。