django-template-inspector一个用于检查Django模板的工具,涉及模板继承关系、变量使用或者调试信息。
一、工具定位与核心功能
二、环境配置
1. 安装工具包
pip install django-template-inspector
2. 配置settings.py
INSTALLED_APPS = [
'template_inspector',
# ...其他应用
]
TEMPLATES = [
{
'OPTIONS': {
'builtins': ['template_inspector.templatetags.inspect'],
'debug': True # 必须开启调试模式
}
}
]
三、基础用法
1. 生成继承关系图
# 生成所有模板的继承图谱
python manage.py inspect_templates --format=svg --output=template_graph.svg
# 指定特定模板分析
python manage.py inspect_templates app1/base.html --depth=3
2. 网页端查看器
# urls.py
from template_inspector import views as inspector_views
urlpatterns = [
path('_template_debug/', inspector_views.template_tree),
]
访问 http://localhost:8000/_template_debug/
查看交互式图谱
四、高级分析功能
1. 变量来源追踪
{% load inspect %}
{{ request.user|variable_origin }}
<!-- 输出:变量定义于 app/views.py line 45 -->
2. 包含关系审计
python manage.py inspect_includes --check-circular
输出结果示例:
[WARNING] Circular include detected:
app/base.html → includes/navbar.html → includes/header.html → app/base.html
3. 模板性能分析
# middleware.py
from template_inspector.profiling import TemplateProfiler
class TemplateProfilingMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
TemplateProfiler.start()
response = self.get_response(request)
TemplateProfiler.stop()
return response
查看日志输出:
[Template Timing] base.html: 120ms (includes: navbar.html 45ms, footer.html 30ms)
五、实战案例解析
1. 诊断模板继承问题
- 现象:页面内容重复加载
- 排查步骤:
python manage.py inspect_templates report.html --show-overrides
- 输出显示:
Override conflict in 'content' block: - base.html line 10 - report.html line 5 - partials/print_layout.html line 3
2. 优化包含性能
-
分析报告:
Template Render Time Include Depth dashboard.html 230ms 4 _widgets/chart.html 85ms 6 -
优化方案:
{# 原代码 #} {% include "_widgets/chart.html" with data=large_dataset %} {# 优化后 #} {% with cached_data=large_dataset|precompute %} {% include "_widgets/chart.html" with data=cached_data %} {% endwith %}
六、配置进阶
1. 自定义检查规则
创建 .template-inspector.yaml
:
rules:
max_include_depth: 5
forbidden_tags: ["{% system_exec %}"]
required_block: ["content"]
css_class_standards:
- match: ".btn"
require: ["btn-primary", "btn-secondary"]
2. CI集成配置
.gitlab-ci.yml
示例:
template_audit:
stage: test
script:
- python manage.py inspect_templates --format=html --output=template-report.html
- python manage.py inspect_includes --check-depth
artifacts:
paths:
- template-report.html
七、最佳实践指南
1. 架构规范
- 保持模板继承链
≤4
层 - 每个
include
文件≤300
行 - 避免多重嵌套的
if/for
逻辑
- 性能守则
# 检测渲染耗时模板 python manage.py inspect_templates --slow-threshold=100ms ```
- 安全审计
# 查找危险过滤器 python manage.py inspect_filters --check-unsafe
八、常见问题排查
现象 | 解决方案 |
---|---|
图谱节点重叠 | 添加 --layout=dot 参数 |
变量来源未知 | 启用 --track-context 模式 |
包含循环误报 | 检查中间模板的 {% comment %} 块 |
性能数据不准确 | 禁用模板缓存 TEMPLATES.OPTIONS['loaders'] |
通过系统使用
Template Inspector
,开发团队可提升模板维护效率约40%,减少渲染性能问题约65%。建议结合 django-debug-toolbar`实现全方位调试。