handlebars-pure-patterns
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseHandlebars Templating Standards
Handlebars 模板规范
The "Logic-less" Philosophy
「无逻辑」设计理念
- Data Preparation: Templates should strictly DISPLAY data. All filtering, sorting, or complex math MUST happen in the application code (Controller/Service) before the data reaches the template.
- Avoid Spaghettis: If you need more than two nested or
{{#if}}blocks, consider refactoring the data structure or creating a custom helper.{{#each}}
- 数据准备: 模板应仅负责展示数据。所有过滤、排序或复杂计算操作必须在数据传入模板前,在应用代码(控制器/服务层)中完成。
- 避免代码混乱: 如果需要嵌套超过两层或
{{#if}}块,请考虑重构数据结构或创建自定义辅助函数。{{#each}}
Syntax & Helpers
语法与辅助函数
- Escaping:
- Default is safe and escapes HTML characters.
{{ value }} - Use (triple-stash) ONLY for trusted HTML strings (e.g., pre-sanitized content).
{{{ value }}}
- Default
- Custom Helpers:
- Do not write complex inline logic. Instead of , create a helper
{{#if (eq (mod index 2) 0)}}or, better yet, pre-calculate{{#if (isEven index)}}in the data model.isEven - Register helpers for formatting dates, currencies, and translation.
- Do not write complex inline logic. Instead of
- 转义处理:
- 默认的会自动转义HTML字符,安全性更高。
{{ value }} - 仅当内容是经过预清理的可信HTML字符串时,才使用(三重花括号)。
{{{ value }}}
- 默认的
- 自定义辅助函数:
- 不要编写复杂的内联逻辑。例如,不要使用,而是创建
{{#if (eq (mod index 2) 0)}}这样的辅助函数,更优的方式是在数据模型中预先计算好{{#if (isEven index)}}字段。isEven - 注册用于日期格式化、货币转换和翻译的辅助函数。
- 不要编写复杂的内联逻辑。例如,不要使用
Component Architecture (Partials)
组件化架构(Partials)
- Atomic Design: Break complex UIs into small files in the directory.
partials/- Naming convention: ,
_card.hbs._navbar.hbs
- Naming convention:
- Context Passing:
- Explicit Context: is preferred over implicit context inheritance.
{{> myPartial specificData }} - Block Partials: Use for wrapping content (like slots).
{{#> layout}} ... {{/layout}}
- Explicit Context:
- 原子化设计: 将复杂UI拆分为小文件,存放在目录下。
partials/- 命名规范:、
_card.hbs。_navbar.hbs
- 命名规范:
- 上下文传递:
- 显式上下文:优先使用,而非隐式上下文继承。
{{> myPartial specificData }} - 块级Partials:使用实现内容包裹(类似插槽功能)。
{{#> layout}} ... {{/layout}}
- 显式上下文:优先使用
Troubleshooting
问题排查
- Missing Properties: Handlebars fails silently on undefined properties. Ensure your data object structure strictly matches the template expectations.
- Prototypes: If using Mongoose/ORMs, convert documents to Plain Old JavaScript Objects (POJOs) (e.g., or
.lean()) before passing to Handlebars to avoid prototype access issues..toJSON()
- 缺失属性: Handlebars对未定义属性会静默失败。确保数据对象结构与模板预期完全匹配。
- 原型访问: 如果使用Mongoose或其他ORM,需先将文档转换为普通JavaScript对象(POJO)(例如通过或
.lean()方法),再传入Handlebars,避免原型访问问题。.toJSON()