handlebars-pure-patterns

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Handlebars Templating Standards

Handlebars 模板规范

The "Logic-less" Philosophy

「无逻辑」设计理念

  1. 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.
  2. Avoid Spaghettis: If you need more than two nested
    {{#if}}
    or
    {{#each}}
    blocks, consider refactoring the data structure or creating a custom helper.
  1. 数据准备: 模板应仅负责展示数据。所有过滤、排序或复杂计算操作必须在数据传入模板前,在应用代码(控制器/服务层)中完成。
  2. 避免代码混乱: 如果需要嵌套超过两层
    {{#if}}
    {{#each}}
    块,请考虑重构数据结构或创建自定义辅助函数。

Syntax & Helpers

语法与辅助函数

  1. Escaping:
    • Default
      {{ value }}
      is safe and escapes HTML characters.
    • Use
      {{{ value }}}
      (triple-stash) ONLY for trusted HTML strings (e.g., pre-sanitized content).
  2. Custom Helpers:
    • Do not write complex inline logic. Instead of
      {{#if (eq (mod index 2) 0)}}
      , create a helper
      {{#if (isEven index)}}
      or, better yet, pre-calculate
      isEven
      in the data model.
    • Register helpers for formatting dates, currencies, and translation.
  1. 转义处理:
    • 默认的
      {{ value }}
      会自动转义HTML字符,安全性更高。
    • 仅当内容是经过预清理的可信HTML字符串时,才使用
      {{{ value }}}
      (三重花括号)。
  2. 自定义辅助函数:
    • 不要编写复杂的内联逻辑。例如,不要使用
      {{#if (eq (mod index 2) 0)}}
      ,而是创建
      {{#if (isEven index)}}
      这样的辅助函数,更优的方式是在数据模型中预先计算好
      isEven
      字段。
    • 注册用于日期格式化、货币转换和翻译的辅助函数。

Component Architecture (Partials)

组件化架构(Partials)

  1. Atomic Design: Break complex UIs into small files in the
    partials/
    directory.
    • Naming convention:
      _card.hbs
      ,
      _navbar.hbs
      .
  2. Context Passing:
    • Explicit Context:
      {{> myPartial specificData }}
      is preferred over implicit context inheritance.
    • Block Partials: Use
      {{#> layout}} ... {{/layout}}
      for wrapping content (like slots).
  1. 原子化设计: 将复杂UI拆分为小文件,存放在
    partials/
    目录下。
    • 命名规范:
      _card.hbs
      _navbar.hbs
  2. 上下文传递:
    • 显式上下文:优先使用
      {{> 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.,
    .lean()
    or
    .toJSON()
    ) before passing to Handlebars to avoid prototype access issues.
  • 缺失属性: Handlebars对未定义属性会静默失败。确保数据对象结构与模板预期完全匹配。
  • 原型访问: 如果使用Mongoose或其他ORM,需先将文档转换为普通JavaScript对象(POJO)(例如通过
    .lean()
    .toJSON()
    方法),再传入Handlebars,避免原型访问问题。