django-templates

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Django Template Patterns

Django 模板模式

Template Organization

模板组织结构

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
Naming conventions:
  • Full pages:
    list.html
    ,
    detail.html
    ,
    form.html
  • HTMX partials:
    _list.html
    ,
    _card.html
    (underscore prefix)
  • Shared partials:
    partials/_navbar.html
    ,
    partials/_pagination.html
  • Components:
    components/_button.html
    ,
    components/_modal.html
templates/
├── base.html              # 站点通用结构的根模板
├── partials/              # 可复用片段(导航栏、页脚、分页)
├── components/            # UI组件(按钮、卡片、模态框)
└── <app>/                 # 应用专属模板
    ├── list.html          # 继承base.html的完整页面
    ├── detail.html
    ├── _list.html         # HTMX局部模板(以下划线为前缀)
    └── _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

Template Inheritance

模板继承

Use three-level inheritance for consistent layouts:
  1. base.html - Site-wide structure (HTML skeleton, navbar, footer)
  2. Section templates - Optional intermediate templates for sections with shared elements
  3. Page templates - Individual pages that extend base or section templates
Standard blocks to define in base.html:
  • title
    - Page title (use
    {{ block.super }}
    to append to site name)
  • content
    - Main page content
  • extra_css
    - Page-specific stylesheets
  • extra_js
    - Page-specific scripts
使用三级继承来保持布局一致性:
  1. base.html - 站点全局结构(HTML骨架、导航栏、页脚)
  2. 板块模板 - 可选的中间层模板,用于包含共享元素的板块
  3. 页面模板 - 继承基础或板块模板的独立页面
base.html中应定义的标准块:
  • title
    - 页面标题(使用
    {{ block.super }}
    来追加站点名称)
  • content
    - 页面主要内容
  • extra_css
    - 页面专属样式表
  • extra_js
    - 页面专属脚本

Partials and Components

局部模板与组件

Partials are template fragments included in other templates. Use for:
  • Repeated content (pagination, empty states)
  • HTMX responses that replace portions of the page
  • Keeping templates DRY
Components are self-contained UI elements with configurable behavior. Pass context with:
  • {% include "components/_button.html" with text="Submit" variant="primary" %}
  • Add
    only
    to isolate context:
    {% include "_card.html" with title=post.title only %}
局部模板是嵌入到其他模板中的模板片段,适用于:
  • 重复出现的内容(分页、空状态)
  • 用于替换页面部分内容的HTMX响应
  • 保持模板代码简洁(DRY原则)
组件是具备可配置行为的独立UI元素,通过以下方式传递上下文:
  • {% include "components/_button.html" with text="Submit" variant="primary" %}
  • 添加
    only
    来隔离上下文:
    {% include "_card.html" with title=post.title only %}

Custom Tags and Filters

自定义标签与过滤器

When to create custom template tags:
  • simple_tag
    - Return a string value (e.g., active link class, formatted output)
  • inclusion_tag
    - Render a template fragment (e.g., pagination component, user avatar)
When to create custom filters:
  • Transform a single value (e.g., initials from name, percentage calculation)
  • Chain with other filters for composable transformations
Location:
apps/<app>/templatetags/<app>_tags.py
(create
__init__.py
in templatetags directory)
何时创建自定义模板标签:
  • simple_tag
    - 返回字符串值(例如,激活链接的类名、格式化输出)
  • inclusion_tag
    - 渲染模板片段(例如,分页组件、用户头像)
何时创建自定义过滤器:
  • 转换单个值(例如,从姓名提取首字母、百分比计算)
  • 可与其他过滤器链式调用,实现组合转换
存放位置:
apps/<app>/templatetags/<app>_tags.py
(需在templatetags目录下创建
__init__.py

Anti-Patterns

反模式

Move logic out of templates:
  • Complex conditionals belong in views or model methods
  • Use
    user.can_moderate
    not
    user.role == "admin" or user.role == "moderator"
Use URL names, not hardcoded paths:
  • Use
    {% url 'posts:detail' pk=post.pk %}
    not
    /posts/{{ post.id }}/
Use CSS classes, not inline styles:
  • Use
    class="error-message"
    not
    style="color: red;"
Handle empty states:
  • Always include
    {% empty %}
    clause in loops that might have no items
将逻辑移出模板:
  • 复杂条件判断应放在视图或模型方法中
  • 使用
    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 %}
    子句

Integration with Other Skills

与其他技能的集成

  • htmx-patterns - HTMX partial templates and dynamic UI
  • django-forms - Form rendering and validation patterns
  • pytest-django-patterns - Testing template rendering
  • htmx-patterns - HTMX局部模板与动态UI
  • django-forms - 表单渲染与验证模式
  • pytest-django-patterns - 模板渲染测试