django模板应保持简洁,复杂逻辑需移至视图或模型;避免模板中嵌套条件、数据库查询和业务判断;善用{% with %}、自定义过滤器和{% empty %}提升可读性、性能与可测性。

模板里别写复杂 if 表达式
Django 模板语言不是 Python,{% if %} 不支持三元运算、嵌套括号或函数调用。比如 {% if user.is_authenticated and (user.profile.level > 5 or user.has_perm('app.view_data')) %} 这种写法会直接报错 —— 模板解析器不认括号分组。
真正可行的只有扁平的 and/or/not,且优先级固定(not > and > or),没法靠括号改顺序。一旦逻辑超过两三个条件,可读性和维护性就崩了。
- 把组合判断逻辑提前移到视图或模型方法里,比如在
User模型加个def can_view_sensitive_data(self):,模板里只写{% if user.can_view_sensitive_data %} - 避免在模板里重复计算,例如
{% if request.user.groups.filter(name='admin').exists %}—— 这会在每次渲染时查一次库,应由视图预计算好传入上下文 - 不要依赖
user.is_staff或user.is_superuser做业务权限判断,它们是 Django 内置标记,和你的业务规则无关
用 with 标签简化重复变量引用
当一个对象属性要被多次使用(比如 {{ order.customer.address.city }} 出现三四次),硬写会冗长且易出错。Django 的 {% with %} 可以临时绑定别名,让模板更干净。
比如:
{% with city=order.customer.address.city country=order.customer.address.country %}<p>City: {{ city }}, Country: {{ country }}</p><div class="aritcle_card flexRow artxards">
<div class="artcardd flexRow">
<a class="aritcle_card_img" rel="nofollow" href="/xiazai/skill8253" title="Django Unfold"><img
src="https://img.php.cn/upload/skill/000/000/081/179195051030769.jpg" alt="Django Unfold" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a rel="nofollow" href="/xiazai/skill8253" title="Django Unfold" class="overflowclass">Django Unfold</a>
<p class="overflowclass">提供使用 django-unfold (v0.56+) 构建高级 Django 管理界面的专业指导。当用户提及 django-unfold、unfold admin 等内容时使用此技能。</p>
</div>
<a rel="nofollow" href="/xiazai/skill8253" title="Django Unfold" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span>
</a>
</div>
</div>{% endwith %}
-
{% with %}仅作用于其内部,不会污染外层上下文 - 不能在
{% with %}里赋值新变量(如status=order.get_status_display是允许的,但count=items|length|add:"1"不行 —— 过滤器链不能用于赋值 - 如果
order.customer.address是 None,city会被设为空字符串,不会抛异常 —— 这点比 Python 安全,但也容易掩盖空值问题
复杂分支用自定义模板过滤器替代嵌套 {% if %}
当需要根据状态显示不同文案(如订单状态:pending → “待确认”,shipped → “已发货”,cancelled → “已取消”),硬写三层 {% if %}{% elif %}{% else %} 很难维护,也违反模板“只负责展示”的原则。
更合理的方式是写一个自定义过滤器:
@register.filterdef display_order_status(value): status_map = { 'pending': '待确认', 'shipped': '已发货', 'cancelled': '已取消', } return status_map.get(value, '未知')然后模板里直接 {{ order.status|display_order_status }}。
- 过滤器逻辑可单元测试,模板保持声明式
- 避免在过滤器里做数据库查询或耗时操作 —— 模板渲染是同步阻塞的,慢一点就拖垮整个页面
- 如果状态映射需动态加载(如从数据库配置表读),应在视图中查好传入,而不是在过滤器里
StatusConfig.objects.get()
列表为空时的处理必须显式写 {% empty %}
{% for item in items %}...{% endfor %} 默认对空列表静默失败 —— 什么也不渲染,连提示都没有。用户看到一片空白,根本不知道是没数据还是加载失败。
正确写法必须带 {% empty %}:
{% for item in items %}<div>{{ item.name }}</div>{% empty %}<p class="empty-tip">暂无数据</p>{% endfor %}
-
{% empty %}是唯一能捕获空序列的机制,{% if items %}不可靠 —— 因为items可能是 QuerySet,未求值前永远为真 - 别在
{% empty %}里放复杂逻辑,它只是兜底文案;真要区分“无权限”和“无数据”,得靠视图层传入不同上下文变量(如has_permission和item_list) - 如果列表来自 API 或缓存,记得在视图里确保它是个真实 list 或 tuple,避免模板里遇到不可迭代对象直接 500
{% if user.is_active and user.profile.verified and not user.banned %} 写单元测试,但你可以给 User.can_access_dashboard() 写三行测试覆盖所有边界。模板越薄,系统越稳。Python免费学习笔记(深入):立即使用
在学习笔记中,你将探索 Python 的核心概念和高级技巧!










