htmx-universal-patterns
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseHTMX Universal Standards
HTMX通用标准
Core Philosophy (HATEOAS)
核心理念(HATEOAS)
- HTML over JSON: The server MUST respond with HTML fragments (partials), not JSON.
- Side Effects via HTML: Do not use client-side logic to update the DOM. Let the server response dictate changes via .
hx-swap
- 优先使用HTML而非JSON:服务器必须返回HTML片段(部分视图),而非JSON。
- 通过HTML处理副作用:不要使用客户端逻辑更新DOM。让服务器响应通过指令决定DOM的变更。
hx-swap
Security & CSRF (Critical)
安全与CSRF防护(关键)
- CSRF Protection: HTMX requests are non-idempotent (POST/PUT/DELETE) and require CSRF protection just like standard forms.
- Header Method: Configure the global to include the token:
hx-headers.<body hx-headers='{"X-CSRF-Token": "{{ csrfToken }}"}'> - Form Method: If headers aren't viable, ensure every includes the hidden CSRF input.
<form>
- Header Method: Configure the global
- XSS Prevention: Since we are injecting HTML, ensure all user content rendered on the server is strictly escaped before reaching the client.
- CSRF防护:HTMX的非幂等请求(POST/PUT/DELETE)需要像标准表单一样进行CSRF防护。
- 头部方法:配置全局以包含令牌:
hx-headers。<body hx-headers='{"X-CSRF-Token": "{{ csrfToken }}"}'> - 表单方法:如果无法使用头部,确保每个都包含隐藏的CSRF输入字段。
<form>
- 头部方法:配置全局
- XSS防护:由于我们会注入HTML,确保所有在服务器渲染的用户内容在发送到客户端前都经过严格转义。
Architectural Rules
架构规则
- The "Partial" Rule: Identify strictly which part of the UI needs updating. Create a server route that renders only that component.
- Idempotency: GET requests should never change state. Use POST/PUT/PATCH/DELETE for actions.
- Progressive Enhancement: Design the feature to work with standard HTML forms/links first where possible.
- "部分视图"规则:明确识别UI中需要更新的具体部分。创建仅渲染该组件的服务器路由。
- 幂等性:GET请求绝不能改变状态。使用POST/PUT/PATCH/DELETE处理操作。
- 渐进式增强:尽可能先设计出可通过标准HTML表单/链接正常工作的功能。
UX & Feedback Patterns
用户体验与反馈模式
- Request Indicators: ALWAYS use .
hx-indicator- Pattern:
<button hx-post="..." hx-indicator="#loading-spinner">Save</button>
- Pattern:
- Active States: Use the class or
htmx-addedto manage active states via server rendering.hx-vals
- 请求指示器:务必使用。
hx-indicator- 示例:
<button hx-post="..." hx-indicator="#loading-spinner">保存</button>
- 示例:
- 激活状态:使用类或
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:如果错误需要更新全局元素(如顶部提示框)而非本地目标,使用此响应头。