mcpField
D
django-templates

django-templates

github.com/waldencui开发17869 次安装32 周前更新
代码仓库

关于 django-templates

django-templates 提供组织和编写 Django 模板的模式,涵盖模板继承、可复用片段、标签与过滤器,以及将应用逻辑移出模板的实践。

主要功能

  1. 01组织页面、片段和组件
  2. 02采用分层模板继承
  3. 03向可复用组件传递上下文
  4. 04选择自定义标签和过滤器
  5. 05避免常见模板反模式

适用场景

  1. 01规划 Django 应用的模板结构
  2. 02构建可复用的 HTMX 片段
  3. 03将复杂逻辑移出模板

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/waldencui/claude-code-django --skill django-templates

安装后在 Claude Code 中输入/django-templates确认已加载。

详细介绍

Django 模板模式

模板组织

templates/
├── base.html              # Root template with common structure
├── partials/              # Reusable fragments (navbar, footer, pagination)
├── components/            # UI components (button, card, modal)
└── <app>/                 # App-specific templates
    ├── list.html          # Full pages extend base.html
    ├── detail.html
    ├── _list.html         # HTMX partials (underscore prefix)
    └── _form.html

命名约定:

  • 完整页面:list.html、detail.html、form.html
  • HTMX 局部模板:_list.html、_card.html(以下划线为前缀)
  • 共享局部模板:partials/_navbar.html、partials/_pagination.html
  • 组件:components/_button.html、components/_modal.html

模板继承

使用三级继承来保持布局一致:

  1. base.html - 全站结构(HTML 框架、导航栏、页脚)
  2. 分区模板 - 可选的中间模板,用于包含共享元素的分区
  3. 页面模板 - 继承基础模板或分区模板的各个页面

在 base.html 中定义的标准块:

  • title - 页面标题(使用 {{ block.super }} 将标题追加到站点名称后)
  • content - 页面主体内容
  • extra_css - 页面专属样式表
  • extra_js - 页面专属脚本

局部模板和组件

局部模板是包含在其他模板中的模板片段。适用于:

  • 重复内容(分页、空状态)
  • 用于替换页面部分内容的 HTMX 响应
  • 保持模板 DRY

组件是具有可配置行为的独立 UI 元素。通过以下方式传递上下文:

  • {% include "components/_button.html" with text="Submit" variant="primary" %}
  • 添加 only 以隔离上下文:{% include "_card.html" with title=post.title only %}

自定义标签和过滤器

创建自定义模板标签的场景:

  • simple_tag - 返回字符串值(例如,活动链接类、格式化输出)
  • inclusion_tag - 渲染模板片段(例如,分页组件、用户头像)

创建自定义过滤器的场景:

  • 转换单个值(例如,从姓名提取首字母、计算百分比)
  • 与其他过滤器串联,实现可组合的转换

位置: apps/<app>/templatetags/<app>_tags.py(在 templatetags 目录中创建 __init__.py)

反模式

将逻辑移出模板:

  • 复杂条件判断应放在视图或模型方法中
  • 使用 user.can_moderate,而非 user.role == "admin" or user.role == "moderator"

使用 URL 名称,而非硬编码路径:

  • 使用 {% url 'posts:detail' pk=post.pk %},而非 /posts/{{ post.id }}/

使用 CSS 类,而非内联样式:

  • 使用 class="error-message",而非 style="color: red;"

处理空状态:

  • 对可能没有项目的循环,始终包含 {% empty %} 子句

与其他技能的集成

  • htmx-patterns - HTMX 局部模板和动态 UI
  • django-forms - 表单渲染和验证模式
  • pytest-django-patterns - 测试模板渲染

评论

支持 Markdown