htmx-universal-patterns

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

HTMX Universal Standards

HTMX通用标准

Core Philosophy (HATEOAS)

核心理念(HATEOAS)

  1. HTML over JSON: The server MUST respond with HTML fragments (partials), not JSON.
  2. Side Effects via HTML: Do not use client-side logic to update the DOM. Let the server response dictate changes via
    hx-swap
    .
  1. 优先使用HTML而非JSON:服务器必须返回HTML片段(部分视图),而非JSON。
  2. 通过HTML处理副作用:不要使用客户端逻辑更新DOM。让服务器响应通过
    hx-swap
    指令决定DOM的变更。

Security & CSRF (Critical)

安全与CSRF防护(关键)

  1. CSRF Protection: HTMX requests are non-idempotent (POST/PUT/DELETE) and require CSRF protection just like standard forms.
    • Header Method: Configure the global
      hx-headers
      to include the token:
      <body hx-headers='{"X-CSRF-Token": "{{ csrfToken }}"}'>
      .
    • Form Method: If headers aren't viable, ensure every
      <form>
      includes the hidden CSRF input.
  2. XSS Prevention: Since we are injecting HTML, ensure all user content rendered on the server is strictly escaped before reaching the client.
  1. CSRF防护:HTMX的非幂等请求(POST/PUT/DELETE)需要像标准表单一样进行CSRF防护。
    • 头部方法:配置全局
      hx-headers
      以包含令牌:
      <body hx-headers='{"X-CSRF-Token": "{{ csrfToken }}"}'>
    • 表单方法:如果无法使用头部,确保每个
      <form>
      都包含隐藏的CSRF输入字段。
  2. XSS防护:由于我们会注入HTML,确保所有在服务器渲染的用户内容在发送到客户端前都经过严格转义。

Architectural Rules

架构规则

  1. The "Partial" Rule: Identify strictly which part of the UI needs updating. Create a server route that renders only that component.
  2. Idempotency: GET requests should never change state. Use POST/PUT/PATCH/DELETE for actions.
  3. Progressive Enhancement: Design the feature to work with standard HTML forms/links first where possible.
  1. "部分视图"规则:明确识别UI中需要更新的具体部分。创建仅渲染该组件的服务器路由。
  2. 幂等性:GET请求绝不能改变状态。使用POST/PUT/PATCH/DELETE处理操作。
  3. 渐进式增强:尽可能先设计出可通过标准HTML表单/链接正常工作的功能。

UX & Feedback Patterns

用户体验与反馈模式

  1. Request Indicators: ALWAYS use
    hx-indicator
    .
    • Pattern:
      <button hx-post="..." hx-indicator="#loading-spinner">Save</button>
  2. Active States: Use the
    htmx-added
    class or
    hx-vals
    to manage active states via server rendering.
  1. 请求指示器:务必使用
    hx-indicator
    • 示例:
      <button hx-post="..." hx-indicator="#loading-spinner">保存</button>
  2. 激活状态:使用
    htmx-added
    类或
    hx-vals
    通过服务器渲染管理激活状态。

Error Handling Protocol

错误处理协议

The backend must communicate status via HTTP Codes:
  • 200 OK: Swap content normally.
  • 204 No Content: Do nothing.
  • 422 Unprocessable Entity: Validation error. Swap the form with the HTML containing error messages.
  • HX-Retarget: Use this header if an error requires updating a global element (like a top-level alert) instead of the local target.
后端必须通过HTTP状态码传递状态:
  • 200 OK:正常替换内容。
  • 204 No Content:不执行任何操作。
  • 422 Unprocessable Entity:验证错误。将表单替换为包含错误提示信息的HTML。
  • HX-Retarget:如果错误需要更新全局元素(如顶部提示框)而非本地目标,使用此响应头。