handlebars

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

When to Use

适用场景

Use this skill when:
  • Creating or modifying
    .hbs
    template files
  • Adding new Handlebars helpers or partials
  • Debugging template rendering issues
  • Understanding existing template patterns in Aurora CLI
  • Working with dynamic code generation

在以下场景使用本技能:
  • 创建或修改
    .hbs
    模板文件
  • 添加新的Handlebars助手(helpers)或片段(partials)
  • 调试模板渲染问题
  • 理解Aurora CLI中的现有模板模式
  • 处理动态代码生成

Critical Patterns

核心模式

Aurora CLI Template Engine Setup

Aurora CLI模板引擎配置

The template engine is configured in
src/@cliter/utils/template-engine.ts
:
  • Uses
    handlebars
    library with
    handlebars-helpers
    addon (189+ built-in helpers)
  • Custom helpers are registered in
    src/@cliter/handlebars/helpers/
  • Partials are registered in
    src/@cliter/handlebars/partials/
  • Templates are in
    src/templates/
    (back/, front/, pipeline/)
Important: Aurora CLI includes ALL helpers from the
handlebars-helpers
package automatically. These 189+ helpers are available in every template without any additional configuration.
模板引擎在
src/@cliter/utils/template-engine.ts
中配置:
  • 使用
    handlebars
    库及
    handlebars-helpers
    扩展(包含189+内置助手)
  • 自定义助手在
    src/@cliter/handlebars/helpers/
    中注册
  • 片段(partials)在
    src/@cliter/handlebars/partials/
    中注册
  • 模板文件位于
    src/templates/
    目录下(分为back/、front/、pipeline/子目录)
重要提示:Aurora CLI会自动包含
handlebars-helpers
包中的所有助手。这189+个助手无需额外配置即可在所有模板中使用。

Helper Registration Pattern

助手注册模式

typescript
// src/@cliter/handlebars/helpers/my-helper.ts
import * as handlebars from 'handlebars';

handlebars.registerHelper('myHelper', function(param1: string, param2: any, options)
{
    // options.data.root contains all template data
    // options.fn(this) executes block content
    // options.inverse(this) executes else block
    return result;
});
typescript
// src/@cliter/handlebars/helpers/my-helper.ts
import * as handlebars from 'handlebars';

handlebars.registerHelper('myHelper', function(param1: string, param2: any, options)
{
    // options.data.root包含所有模板数据
    // options.fn(this)执行块内容
    // options.inverse(this)执行else块内容
    return result;
});

Partial Registration Pattern

片段注册模式

typescript
// src/@cliter/handlebars/partials/my-partial.ts
import * as handlebars from 'handlebars';

handlebars.registerPartial('myPartial', `
{{#each items}}
    {{ this.name }}
{{/each}}
`);

typescript
// src/@cliter/handlebars/partials/my-partial.ts
import * as handlebars from 'handlebars';

handlebars.registerPartial('myPartial', `
{{#each items}}
    {{ this.name }}
{{/each}}
`);

Handlebars Syntax Guide

Handlebars语法指南

Basic Expressions

基础表达式

handlebars
{{! Comment - not rendered }}
{{ variable }}                    {{! Simple output }}
{{{ rawHtml }}}                   {{! Unescaped HTML }}
{{ helper param1 param2 }}        {{! Helper call }}
{{ object.property }}             {{! Property access }}
{{ ../parentContext }}            {{! Parent context access }}
handlebars
{{! 注释 - 不会被渲染 }}
{{ variable }}                    {{! 简单输出 }}
{{{ rawHtml }}}                   {{! 不转义HTML }}
{{ helper param1 param2 }}        {{! 调用助手 }}
{{ object.property }}             {{! 属性访问 }}
{{ ../parentContext }}            {{! 父上下文访问 }}

Whitespace Control

空白字符控制

handlebars
{{~expression}}     {{! Trim whitespace before }}
{{expression~}}     {{! Trim whitespace after }}
{{~expression~}}    {{! Trim both sides }}
handlebars
{{~expression}}     {{! 移除表达式前的空白字符 }}
{{expression~}}     {{! 移除表达式后的空白字符 }}
{{~expression~}}    {{! 移除表达式两侧的空白字符 }}

Block Helpers

块级助手

handlebars
{{#if condition}}
    content if true
{{else}}
    content if false
{{/if}}

{{#each array}}
    {{@index}} - {{@first}} - {{@last}} - {{this}}
{{/each}}

{{#unless condition}}
    content if false
{{/unless}}

{{#with object}}
    {{property}}  {{! Access object.property }}
{{/with}}
handlebars
{{#if condition}}
    条件为真时显示的内容
{{else}}
    条件为假时显示的内容
{{/if}}

{{#each array}}
    {{@index}} - {{@first}} - {{@last}} - {{this}}
{{/each}}

{{#unless condition}}
    条件为假时显示的内容
{{/unless}}

{{#with object}}
    {{property}}  {{! 访问object.property }}
{{/with}}

Custom Block Helpers (Aurora CLI)

自定义块级助手(Aurora CLI)

handlebars
{{#loops 10}}
    {{@index}} {{@first}} {{@last}}
{{/loops}}

{{#eq value1 value2}}
    content if equal
{{/eq}}

{{#unlessEq value1 value2}}
    content if not equal
{{/unlessEq}}

handlebars
{{#loops 10}}
    {{@index}} {{@first}} {{@last}}
{{/loops}}

{{#eq value1 value2}}
    值相等时显示的内容
{{/eq}}

{{#unlessEq value1 value2}}
    值不相等时显示的内容
{{/unlessEq}}

Aurora CLI Helper Categories

Aurora CLI助手分类

String Transformation Helpers

字符串转换助手

HelperDescriptionExample
toCamelCase
Convert to camelCase
{{ toCamelCase "my_name" }}
myName
toPascalCase
Convert to PascalCase
{{ toPascalCase "my_name" }}
MyName
toKebabCase
Convert to kebab-case
{{ toKebabCase "myName" }}
my-name
toSnakeCase
Convert to snake_case
{{ toSnakeCase "myName" }}
my_name
sumStrings
Concatenate strings
{{ sumStrings "Hello" " " "World" }}
singleLine
Remove line breaks
{{ singleLine multiLineText }}
助手说明示例
toCamelCase
转换为camelCase格式
{{ toCamelCase "my_name" }}
myName
toPascalCase
转换为PascalCase格式
{{ toPascalCase "my_name" }}
MyName
toKebabCase
转换为kebab-case格式
{{ toKebabCase "myName" }}
my-name
toSnakeCase
转换为snake_case格式
{{ toSnakeCase "myName" }}
my_name
sumStrings
字符串拼接
{{ sumStrings "Hello" " " "World" }}
singleLine
移除换行符
{{ singleLine multiLineText }}

Variable Management Helpers

变量管理助手

handlebars
{{! Set a variable in root context }}
{{ setVar 'myVar' 'value' }}
{{ setVar 'myVar' (someHelper param) }}

{{! Use the variable }}
{{ myVar }}
handlebars
{{! 在根上下文中设置变量 }}
{{ setVar 'myVar' 'value' }}
{{ setVar 'myVar' (someHelper param) }}

{{! 使用变量 }}
{{ myVar }}

Array/Object Helpers

数组/对象助手

handlebars
{{! Create an array }}
{{ setVar 'items' (array 'item1' 'item2' 'item3') }}

{{! Create an object }}
{{ setVar 'obj' (object key1='value1' key2='value2') }}

{{! Push to array }}
{{ push myArray (object name='newItem') }}

{{! Check if has items }}
{{#if (hasItems myArray)}}
    has items
{{/if}}
handlebars
{{! 创建数组 }}
{{ setVar 'items' (array 'item1' 'item2' 'item3') }}

{{! 创建对象 }}
{{ setVar 'obj' (object key1='value1' key2='value2') }}

{{! 向数组中添加元素 }}
{{ push myArray (object name='newItem') }}

{{! 检查数组是否有元素 }}
{{#if (hasItems myArray)}}
    包含元素
{{/if}}

Conditional Helpers

条件判断助手

handlebars
{{! Ternary operator }}
{{ ternary condition 'trueValue' 'falseValue' }}

{{! Check if undefined }}
{{#if (isUndefined variable)}}
    is undefined
{{/if}}

{{! Not in array }}
{{#if (notInArray item array)}}
    not in array
{{/if}}
handlebars
{{! 三元运算符 }}
{{ ternary condition 'trueValue' 'falseValue' }}

{{! 检查是否为undefined }}
{{#if (isUndefined variable)}}
    是undefined
{{/if}}

{{! 检查元素是否不在数组中 }}
{{#if (notInArray item array)}}
    不在数组中
{{/if}}

Property Filter Helpers

属性过滤助手

Most property helpers filter
schema.aggregateProperties
:
handlebars
{{! Get properties without timestamps }}
{{#each (getWithoutTimestampsProperties schema.aggregateProperties)}}
    {{ name }}
{{/each}}

{{! Get enum properties }}
{{#each (getEnumProperties schema.aggregateProperties)}}
    {{ name }}: {{ type }}
{{/each}}

{{! Get relationship properties }}
{{#each (getWithRelationshipOneToOneProperties schema.aggregateProperties)}}
    {{ relationship.aggregateName }}
{{/each}}
大多数属性助手用于过滤
schema.aggregateProperties
handlebars
{{! 获取不含时间戳的属性 }}
{{#each (getWithoutTimestampsProperties schema.aggregateProperties)}}
    {{ name }}
{{/each}}

{{! 获取枚举属性 }}
{{#each (getEnumProperties schema.aggregateProperties)}}
    {{ name }}: {{ type }}
{{/each}}

{{! 获取关联属性(一对一) }}
{{#each (getWithRelationshipOneToOneProperties schema.aggregateProperties)}}
    {{ relationship.aggregateName }}
{{/each}}

Import Manager Helper

导入管理助手

handlebars
{{! Initialize imports array }}
{{
    setVar 'importsArray' (
        array
            (object items=(array 'Injectable') path='@nestjs/common')
            (object items='MyClass' path='./my-class')
    )
~}}

{{! Add more imports dynamically }}
{{
    push importsArray
        (object items='AnotherClass' path='./another')
~}}

{{! Render all imports }}
{{{ importManager (object imports=importsArray) }}}
handlebars
{{! 初始化导入数组 }}
{{
    setVar 'importsArray' (
        array
            (object items=(array 'Injectable') path='@nestjs/common')
            (object items='MyClass' path='./my-class')
    )
~}}

{{! 动态添加更多导入 }}
{{
    push importsArray
        (object items='AnotherClass' path='./another')
~}}

{{! 渲染所有导入语句 }}
{{{ importManager (object imports=importsArray) }}}

ID Generation Helpers

ID生成助手

handlebars
{{ uuid 'fieldName' }}           {{! Generate deterministic UUID }}
{{ nanoid 'fieldName' }}         {{! Generate NanoID }}
{{ randomIntegerDigits 5 }}      {{! Random integer with N digits }}
{{ randomDecimalDigits 2 3 }}    {{! Random decimal (int.dec) }}

handlebars
{{ uuid 'fieldName' }}           {{! 生成确定性UUID }}
{{ nanoid 'fieldName' }}         {{! 生成NanoID }}
{{ randomIntegerDigits 5 }}      {{! 生成指定位数的随机整数 }}
{{ randomDecimalDigits 2 3 }}    {{! 生成随机小数(整数部分.小数部分) }}

Handlebars-Helpers Package (Built-in)

Handlebars-Helpers包(内置)

Aurora CLI includes all 189+ helpers from the
handlebars-helpers
package. These are available automatically in all templates.
Aurora CLI包含
handlebars-helpers
包中的所有189+个助手。这些助手可直接在所有模板中使用,无需额外配置。

String Helpers (36 helpers)

字符串助手(36个)

handlebars
{{ append "hello" " world" }}        {{! "hello world" }}
{{ camelcase "foo bar" }}            {{! "fooBar" }}
{{ capitalize "hello" }}             {{! "Hello" }}
{{ capitalizeAll "hello world" }}    {{! "Hello World" }}
{{ dashcase "fooBar" }}              {{! "foo-bar" }}
{{ dotcase "fooBar" }}               {{! "foo.bar" }}
{{ ellipsis "long text..." 10 }}     {{! "long te..." }}
{{ hyphenate "foo bar" }}            {{! "foo-bar" }}
{{ lowercase "HELLO" }}              {{! "hello" }}
{{ pascalcase "foo bar" }}           {{! "FooBar" }}
{{ pathcase "fooBar" }}              {{! "foo/bar" }}
{{ prepend "world" "hello " }}       {{! "hello world" }}
{{ remove "foobar" "bar" }}          {{! "foo" }}
{{ replace "foobar" "bar" "baz" }}   {{! "foobaz" }}
{{ reverse "abc" }}                  {{! "cba" }}
{{ sentence "hello. world" }}        {{! "Hello. World" }}
{{ snakecase "fooBar" }}             {{! "foo_bar" }}
{{ split "a,b,c" "," }}              {{! ["a","b","c"] }}
{{ startsWith "hello" "he" }}        {{! true }}
{{ titleize "hello world" }}         {{! "Hello World" }}
{{ trim "  hello  " }}               {{! "hello" }}
{{ truncate "long text" 5 }}         {{! "long..." }}
{{ truncateWords "a b c d" 2 }}      {{! "a b..." }}
{{ uppercase "hello" }}              {{! "HELLO" }}
{{ center "text" 10 }}               {{! Centers with spaces }}
{{#isString value}}is string{{/isString}}
handlebars
{{ append "hello" " world" }}        {{! "hello world" }}
{{ camelcase "foo bar" }}            {{! "fooBar" }}
{{ capitalize "hello" }}             {{! "Hello" }}
{{ capitalizeAll "hello world" }}    {{! "Hello World" }}
{{ dashcase "fooBar" }}              {{! "foo-bar" }}
{{ dotcase "fooBar" }}               {{! "foo.bar" }}
{{ ellipsis "long text..." 10 }}     {{! "long te..." }}
{{ hyphenate "foo bar" }}            {{! "foo-bar" }}
{{ lowercase "HELLO" }}              {{! "hello" }}
{{ pascalcase "foo bar" }}           {{! "FooBar" }}
{{ pathcase "fooBar" }}              {{! "foo/bar" }}
{{ prepend "world" "hello " }}       {{! "hello world" }}
{{ remove "foobar" "bar" }}          {{! "foo" }}
{{ replace "foobar" "bar" "baz" }}   {{! "foobaz" }}
{{ reverse "abc" }}                  {{! "cba" }}
{{ sentence "hello. world" }}        {{! "Hello. World" }}
{{ snakecase "fooBar" }}             {{! "foo_bar" }}
{{ split "a,b,c" "," }}              {{! ["a","b","c"] }}
{{ startsWith "hello" "he" }}        {{! true }}
{{ titleize "hello world" }}         {{! "Hello World" }}
{{ trim "  hello  " }}               {{! "hello" }}
{{ truncate "long text" 5 }}         {{! "long..." }}
{{ truncateWords "a b c d" 2 }}      {{! "a b..." }}
{{ uppercase "hello" }}              {{! "HELLO" }}
{{ center "text" 10 }}               {{! 用空格居中 }}
{{#isString value}}是字符串{{/isString}}

Array Helpers (28 helpers)

数组助手(28个)

handlebars
{{ after myArray 2 }}                {{! Items after index 2 }}
{{ arrayify value }}                 {{! Converts to array }}
{{ before myArray 3 }}               {{! First 3 items }}
{{ first myArray }}                  {{! First item }}
{{ first myArray 3 }}                {{! First 3 items }}
{{ last myArray }}                   {{! Last item }}
{{ last myArray 2 }}                 {{! Last 2 items }}
{{ length myArray }}                 {{! Array length }}
{{ join myArray ", " }}              {{! "a, b, c" }}
{{ reverse myArray }}                {{! Reversed array }}
{{ sort myArray }}                   {{! Sorted array }}
{{ sortBy myArray "name" }}          {{! Sort by property }}
{{ unique myArray }}                 {{! Remove duplicates }}
{{ itemAt myArray 2 }}               {{! Item at index 2 }}
{{ pluck users "name" }}             {{! Extract "name" from objects }}
{{#inArray "a" myArray}}found{{/inArray}}
{{#isArray value}}is array{{/isArray}}
{{#equalsLength myArray 5}}has 5{{/equalsLength}}

{{#forEach myArray}}
  {{@index}} {{@first}} {{@last}} {{this}}
{{/forEach}}

{{#eachIndex myArray}}
  {{item}} at {{index}}
{{/eachIndex}}

{{#filter myArray}}{{/filter}}
{{#map myArray}}{{/map}}
{{#some myArray}}{{/some}}
{{#withFirst myArray}}{{this}}{{/withFirst}}
{{#withLast myArray 2}}{{this}}{{/withLast}}
{{#withGroup myArray 3}}{{this}}{{/withGroup}}
{{#withSort myArray "name"}}{{this}}{{/withSort}}
handlebars
{{ after myArray 2 }}                {{! 索引2之后的元素 }}
{{ arrayify value }}                 {{! 转换为数组 }}
{{ before myArray 3 }}               {{! 前3个元素 }}
{{ first myArray }}                  {{! 第一个元素 }}
{{ first myArray 3 }}                {{! 前3个元素 }}
{{ last myArray }}                   {{! 最后一个元素 }}
{{ last myArray 2 }}                 {{! 最后2个元素 }}
{{ length myArray }}                 {{! 数组长度 }}
{{ join myArray ", " }}              {{! "a, b, c" }}
{{ reverse myArray }}                {{! 反转数组 }}
{{ sort myArray }}                   {{! 排序数组 }}
{{ sortBy myArray "name" }}          {{! 按属性排序 }}
{{ unique myArray }}                 {{! 移除重复元素 }}
{{ itemAt myArray 2 }}               {{! 索引2处的元素 }}
{{ pluck users "name" }}             {{! 提取对象中的"name"属性 }}
{{#inArray "a" myArray}}找到元素{{/inArray}}
{{#isArray value}}是数组{{/isArray}}
{{#equalsLength myArray 5}}包含5个元素{{/equalsLength}}

{{#forEach myArray}}
  {{@index}} {{@first}} {{@last}} {{this}}
{{/forEach}}

{{#eachIndex myArray}}
  {{item}} 位于索引 {{index}}
{{/eachIndex}}

{{#filter myArray}}{{/filter}}
{{#map myArray}}{{/map}}
{{#some myArray}}{{/some}}
{{#withFirst myArray}}{{this}}{{/withFirst}}
{{#withLast myArray 2}}{{this}}{{/withLast}}
{{#withGroup myArray 3}}{{this}}{{/withGroup}}
{{#withSort myArray "name"}}{{this}}{{/withSort}}

Comparison Helpers (24 helpers)

比较助手(24个)

handlebars
{{#and value1 value2}}both truthy{{/and}}
{{#or value1 value2}}at least one truthy{{/or}}
{{#not value}}falsey{{/not}}
{{#eq a b}}equal{{/eq}}
{{#is a b}}loosely equal{{/is}}
{{#isnt a b}}not equal{{/isnt}}
{{#gt a b}}greater than{{/gt}}
{{#gte a b}}greater or equal{{/gte}}
{{#lt a b}}less than{{/lt}}
{{#lte a b}}less or equal{{/lte}}
{{#compare a ">" b}}comparison{{/compare}}
{{#contains collection value}}found{{/contains}}
{{#has value pattern}}matches{{/has}}
{{#ifEven num}}even{{/ifEven}}
{{#ifOdd num}}odd{{/ifOdd}}
{{#ifNth 10 2}}every 2nd{{/ifNth}}
{{#isTruthy value}}truthy{{/isTruthy}}
{{#isFalsey value}}falsey{{/isFalsey}}
{{#neither a b}}both falsey{{/neither}}
{{ default value "fallback" }}       {{! Returns fallback if undefined }}
{{#unlessEq a b}}not equal{{/unlessEq}}
{{#unlessGt a b}}not greater{{/unlessGt}}
{{#unlessLt a b}}not less{{/unlessLt}}
handlebars
{{#and value1 value2}}两者都为真{{/and}}
{{#or value1 value2}}至少一个为真{{/or}}
{{#not value}}为假{{/not}}
{{#eq a b}}相等{{/eq}}
{{#is a b}}松散相等{{/is}}
{{#isnt a b}}不相等{{/isnt}}
{{#gt a b}}大于{{/gt}}
{{#gte a b}}大于等于{{/gte}}
{{#lt a b}}小于{{/lt}}
{{#lte a b}}小于等于{{/lte}}
{{#compare a ">" b}}比较结果为真{{/compare}}
{{#contains collection value}}找到元素{{/contains}}
{{#has value pattern}}匹配模式{{/has}}
{{#ifEven num}}偶数{{/ifEven}}
{{#ifOdd num}}奇数{{/ifOdd}}
{{#ifNth 10 2}}每第2个元素{{/ifNth}}
{{#isTruthy value}}为真值{{/isTruthy}}
{{#isFalsey value}}为假值{{/isFalsey}}
{{#neither a b}}两者都为假{{/neither}}
{{ default value "fallback" }}       {{! 如果value为undefined则返回fallback }}
{{#unlessEq a b}}不相等{{/unlessEq}}
{{#unlessGt a b}}不大于{{/unlessGt}}
{{#unlessLt a b}}不小于{{/unlessLt}}

Math Helpers (16 helpers)

数学助手(16个)

handlebars
{{ abs -5 }}                         {{! 5 }}
{{ add 1 2 }}                        {{! 3 }}
{{ subtract 5 2 }}                   {{! 3 }}
{{ multiply 3 4 }}                   {{! 12 }}
{{ divide 10 2 }}                    {{! 5 }}
{{ modulo 10 3 }}                    {{! 1 }}
{{ ceil 4.3 }}                       {{! 5 }}
{{ floor 4.7 }}                      {{! 4 }}
{{ round 4.5 }}                      {{! 5 }}
{{ avg myNumbers }}                  {{! Average of array }}
{{ sum myNumbers }}                  {{! Sum of array }}
{{ random 1 100 }}                   {{! Random between 1-100 }}
{{ plus 1 2 }}                       {{! Alias for add }}
{{ minus 5 2 }}                      {{! Alias for subtract }}
{{ times 3 4 }}                      {{! Alias for multiply }}
{{ remainder 10 3 }}                 {{! Alias for modulo }}
handlebars
{{ abs -5 }}                         {{! 5 }}
{{ add 1 2 }}                        {{! 3 }}
{{ subtract 5 2 }}                   {{! 3 }}
{{ multiply 3 4 }}                   {{! 12 }}
{{ divide 10 2 }}                    {{! 5 }}
{{ modulo 10 3 }}                    {{! 1 }}
{{ ceil 4.3 }}                       {{! 5 }}
{{ floor 4.7 }}                      {{! 4 }}
{{ round 4.5 }}                      {{! 5 }}
{{ avg myNumbers }}                  {{! 数组平均值 }}
{{ sum myNumbers }}                  {{! 数组求和 }}
{{ random 1 100 }}                   {{! 1-100之间的随机数 }}
{{ plus 1 2 }}                       {{! add的别名 }}
{{ minus 5 2 }}                      {{! subtract的别名 }}
{{ times 3 4 }}                      {{! multiply的别名 }}
{{ remainder 10 3 }}                 {{! modulo的别名 }}

Number Helpers (9 helpers)

数字助手(9个)

handlebars
{{ bytes 1024 }}                     {{! "1 KB" }}
{{ addCommas 1000000 }}              {{! "1,000,000" }}
{{ phoneNumber "1234567890" }}       {{! "(123) 456-7890" }}
{{ toAbbr 1000000 }}                 {{! "1m" }}
{{ toExponential 12345 2 }}          {{! "1.23e+4" }}
{{ toFixed 3.14159 2 }}              {{! "3.14" }}
{{ toFloat "3.14" }}                 {{! 3.14 }}
{{ toInt "42" }}                     {{! 42 }}
{{ toPrecision 3.14159 3 }}          {{! "3.14" }}
handlebars
{{ bytes 1024 }}                     {{! "1 KB" }}
{{ addCommas 1000000 }}              {{! "1,000,000" }}
{{ phoneNumber "1234567890" }}       {{! "(123) 456-7890" }}
{{ toAbbr 1000000 }}                 {{! "1m" }}
{{ toExponential 12345 2 }}          {{! "1.23e+4" }}
{{ toFixed 3.14159 2 }}              {{! "3.14" }}
{{ toFloat "3.14" }}                 {{! 3.14 }}
{{ toInt "42" }}                     {{! 42 }}
{{ toPrecision 3.14159 3 }}          {{! "3.14" }}

Object Helpers (14 helpers)

对象助手(14个)

handlebars
{{ get object "nested.path" }}       {{! Get nested value }}
{{ getObject object "key" }}         {{! Get key-value pair }}
{{ JSONstringify object }}           {{! JSON string }}
{{ JSONparse jsonString }}           {{! Parse JSON }}
{{ stringify value }}                {{! String representation }}
{{#hasOwn object "key"}}has key{{/hasOwn}}
{{#isObject value}}is object{{/isObject}}
{{#forIn object}}{{@key}}: {{this}}{{/forIn}}
{{#forOwn object}}{{@key}}: {{this}}{{/forOwn}}
{{#extend obj1 obj2}}{{/extend}}
{{#merge obj1 obj2}}{{/merge}}
{{#pick context "a" "b"}}{{/pick}}
{{ toPath "a" "b" "c" }}             {{! "a.b.c" }}
handlebars
{{ get object "nested.path" }}       {{! 获取嵌套属性值 }}
{{ getObject object "key" }}         {{! 获取键值对 }}
{{ JSONstringify object }}           {{! JSON字符串 }}
{{ JSONparse jsonString }}           {{! 解析JSON }}
{{ stringify value }}                {{! 字符串表示 }}
{{#hasOwn object "key"}}包含该键{{/hasOwn}}
{{#isObject value}}是对象{{/isObject}}
{{#forIn object}}{{@key}}: {{this}}{{/forIn}}
{{#forOwn object}}{{@key}}: {{this}}{{/forOwn}}
{{#extend obj1 obj2}}{{/extend}}
{{#merge obj1 obj2}}{{/merge}}
{{#pick context "a" "b"}}{{/pick}}
{{ toPath "a" "b" "c" }}             {{! "a.b.c" }}

URL Helpers (9 helpers)

URL助手(9个)

handlebars
{{ encodeURI "hello world" }}        {{! "hello%20world" }}
{{ decodeURI "hello%20world" }}      {{! "hello world" }}
{{ escape value }}                   {{! URL escaped }}
{{ urlResolve base path }}           {{! Resolved URL }}
{{ urlParse url }}                   {{! Parsed URL object }}
{{ stripQuerystring url }}           {{! URL without query }}
{{ stripProtocol url }}              {{! URL without protocol }}
{{ url_encode value }}               {{! Alias for encodeURI }}
{{ url_decode value }}               {{! Alias for decodeURI }}
handlebars
{{ encodeURI "hello world" }}        {{! "hello%20world" }}
{{ decodeURI "hello%20world" }}      {{! "hello world" }}
{{ escape value }}                   {{! URL转义 }}
{{ urlResolve base path }}           {{! 解析URL }}
{{ urlParse url }}                   {{! 解析URL对象 }}
{{ stripQuerystring url }}           {{! 移除查询参数的URL }}
{{ stripProtocol url }}              {{! 移除协议的URL }}
{{ url_encode value }}               {{! encodeURI的别名 }}
{{ url_decode value }}               {{! decodeURI的别名 }}

Date Helpers (3 helpers)

日期助手(3个)

handlebars
{{ year }}                           {{! Current year }}
{{ date }}                           {{! Current date }}
{{ moment date "YYYY-MM-DD" }}       {{! Format with moment.js }}
handlebars
{{ year }}                           {{! 当前年份 }}
{{ date }}                           {{! 当前日期 }}
{{ moment date "YYYY-MM-DD" }}       {{! 使用moment.js格式化日期 }}

Path Helpers (8 helpers)

路径助手(8个)

handlebars
{{ basename "/a/b/file.txt" }}       {{! "file.txt" }}
{{ dirname "/a/b/file.txt" }}        {{! "/a/b" }}
{{ extname "file.txt" }}             {{! ".txt" }}
{{ stem "file.txt" }}                {{! "file" }}
{{ resolve "a" "b" "c" }}            {{! Absolute path }}
{{ relative "/a/b" "/a/c" }}         {{! "../c" }}
{{ segments path 0 2 }}              {{! Path segments range }}
{{ absolute path 1 }}                {{! Directory segment }}
handlebars
{{ basename "/a/b/file.txt" }}       {{! "file.txt" }}
{{ dirname "/a/b/file.txt" }}        {{! "/a/b" }}
{{ extname "file.txt" }}             {{! ".txt" }}
{{ stem "file.txt" }}                {{! "file" }}
{{ resolve "a" "b" "c" }}            {{! 绝对路径 }}
{{ relative "/a/b" "/a/c" }}         {{! "../c" }}
{{ segments path 0 2 }}              {{! 路径片段范围 }}
{{ absolute path 1 }}                {{! 目录片段 }}

Collection Helpers (2 helpers)

集合助手(2个)

handlebars
{{#isEmpty collection}}empty{{/isEmpty}}
{{#iterate collection}}{{this}}{{/iterate}}
handlebars
{{#isEmpty collection}}集合为空{{/isEmpty}}
{{#iterate collection}}{{this}}{{/iterate}}

Inflection Helpers (2 helpers)

词形变化助手(2个)

handlebars
{{ inflect count "item" "items" }}   {{! Pluralization }}
{{ ordinalize 1 }}                   {{! "1st" }}
{{ ordinalize 22 }}                  {{! "22nd" }}
handlebars
{{ inflect count "item" "items" }}   {{! 复数化 }}
{{ ordinalize 1 }}                   {{! "1st" }}
{{ ordinalize 22 }}                  {{! "22nd" }}

Regex Helpers (2 helpers)

正则表达式助手(2个)

handlebars
{{ toRegex "pattern" "gi" }}         {{! Creates RegExp }}
{{#test "hello" "ell"}}matches{{/test}}
handlebars
{{ toRegex "pattern" "gi" }}         {{! 创建正则表达式 }}
{{#test "hello" "ell"}}匹配{{/test}}

HTML Helpers (7 helpers)

HTML助手(7个)

handlebars
{{ sanitize "<b>text</b>" }}         {{! "text" }}
{{{ ul myArray }}}                   {{! <ul><li>...</li></ul> }}
{{{ ol myArray }}}                   {{! <ol><li>...</li></ol> }}
{{{ css "styles.css" }}}             {{! <link rel="stylesheet"...> }}
{{{ js "script.js" }}}               {{! <script src="..."></script> }}
{{ attr attributes }}                {{! Stringifies HTML attributes }}
{{ thumbnailImage image }}           {{! Figure with thumbnail }}
handlebars
{{ sanitize "<b>text</b>" }}         {{! "text" }}
{{{ ul myArray }}}                   {{! <ul><li>...</li></ul> }}
{{{ ol myArray }}}                   {{! <ol><li>...</li></ol> }}
{{{ css "styles.css" }}}             {{! <link rel="stylesheet"...> }}
{{{ js "script.js" }}}               {{! <script src="..."></script> }}
{{ attr attributes }}                {{! 转换为HTML属性字符串 }}
{{ thumbnailImage image }}           {{! 带缩略图的figure标签 }}

Markdown Helpers (2 helpers)

Markdown助手(2个)

handlebars
{{{ markdown "**bold**" }}}          {{! <strong>bold</strong> }}
{{{ md "./file.md" }}}               {{! Rendered markdown file }}
handlebars
{{{ markdown "**bold**" }}}          {{! <strong>bold</strong> }}
{{{ md "./file.md" }}}               {{! 渲染Markdown文件 }}

Misc Helpers (5 helpers)

其他助手(5个)

handlebars
{{ typeOf value }}                   {{! "string", "array", etc. }}
{{ noop }}                           {{! Renders block without processing }}
{{ option "key" }}                   {{! Get value from options }}
{{#withHash key="value"}}{{key}}{{/withHash}}
{{ frame }}                          {{! Frame-related helper }}
handlebars
{{ typeOf value }}                   {{! "string", "array"等类型 }}
{{ noop }}                           {{! 渲染块内容但不处理 }}
{{ option "key" }}                   {{! 从选项中获取值 }}
{{#withHash key="value"}}{{key}}{{/withHash}}
{{ frame }}                          {{! 框架相关助手 }}

Logging Helpers (11 helpers)

日志助手(11个)

handlebars
{{ log "message" }}                  {{! Console log }}
{{ info "info message" }}            {{! Info level }}
{{ warn "warning" }}                 {{! Warning level }}
{{ error "error" }}                  {{! Error level }}
{{ success "done" }}                 {{! Success message }}
{{ ok "ok" }}                        {{! Ok message }}
{{ danger "danger" }}                {{! Danger message }}
{{ bold "text" }}                    {{! Bold formatting }}
{{ _debug value }}                   {{! Debug output }}
{{ _inspect value }}                 {{! Inspect value }}
Full Reference: See references/handlebars-helpers-reference.md for complete documentation.

handlebars
{{ log "message" }}                  {{! 控制台日志 }}
{{ info "info message" }}            {{! 信息级别日志 }}
{{ warn "warning" }}                 {{! 警告级别日志 }}
{{ error "error" }}                  {{! 错误级别日志 }}
{{ success "done" }}                 {{! 成功消息 }}
{{ ok "ok" }}                        {{! 确认消息 }}
{{ danger "danger" }}                {{! 危险提示 }}
{{ bold "text" }}                    {{! 加粗格式 }}
{{ _debug value }}                   {{! 调试输出 }}
{{ _inspect value }}                 {{! 检查值 }}
完整参考:请查看references/handlebars-helpers-reference.md获取完整文档。

Decision Tree

决策树

Need string transformation? → toCamelCase, toPascalCase, toKebabCase, toSnakeCase (Aurora)
                           → camelcase, pascalcase, snakecase, dashcase (handlebars-helpers)
Need to store temporary data? → setVar
Need to build arrays/objects? → array, object, push
Need conditional rendering? → if, unless, eq, unlessEq, ternary, and, or, not, compare
Need to iterate? → each, loops, forEach, eachIndex, forIn, forOwn
Need to filter properties? → get*Properties helpers (Aurora custom)
Need to manage imports? → importManager with importsArray
Need unique IDs? → uuid, nanoid
Need math operations? → add, subtract, multiply, divide, ceil, floor, round
Need string manipulation? → trim, split, replace, truncate, append, prepend
Need array operations? → first, last, sort, unique, filter, map, join
Need object access? → get, hasOwn, forIn, forOwn
Need URL handling? → encodeURI, decodeURI, urlParse, stripQuerystring
Need path operations? → basename, dirname, extname, resolve

需要字符串转换? → toCamelCase, toPascalCase, toKebabCase, toSnakeCase(Aurora自定义)
                           → camelcase, pascalcase, snakecase, dashcase(handlebars-helpers内置)
需要存储临时数据? → setVar
需要构建数组/对象? → array, object, push
需要条件渲染? → if, unless, eq, unlessEq, ternary, and, or, not, compare
需要遍历? → each, loops, forEach, eachIndex, forIn, forOwn
需要过滤属性? → get*Properties系列助手(Aurora自定义)
需要管理导入? → importManager结合importsArray
需要生成唯一ID? → uuid, nanoid
需要数学运算? → add, subtract, multiply, divide, ceil, floor, round
需要字符串操作? → trim, split, replace, truncate, append, prepend
需要数组操作? → first, last, sort, unique, filter, map, join
需要对象访问? → get, hasOwn, forIn, forOwn
需要URL处理? → encodeURI, decodeURI, urlParse, stripQuerystring
需要路径操作? → basename, dirname, extname, resolve

Code Examples

代码示例

Example 1: Creating a New Helper

示例1:创建新助手

typescript
// src/@cliter/handlebars/helpers/is-required-property.ts
import * as handlebars from 'handlebars';
import { Property } from '../../types';

handlebars.registerHelper('isRequiredProperty', function(
    property: Property,
)
{
    return !property.nullable && !property.hasOwnProperty('defaultValue');
});
typescript
// src/@cliter/handlebars/helpers/is-required-property.ts
import * as handlebars from 'handlebars';
import { Property } from '../../types';

handlebars.registerHelper('isRequiredProperty', function(
    property: Property,
)
{
    return !property.nullable && !property.hasOwnProperty('defaultValue');
});

Example 2: Using Multiple Helpers in Template

示例2:在模板中使用多个助手

handlebars
{{! Generate TypeScript interface }}
export interface {{ toPascalCase schema.moduleName }}Input
{
{{#each (getWithoutTimestampsProperties schema.aggregateProperties)}}
    {{ toCamelCase name }}{{#if nullable}}?{{/if}}: {{ getDtoTypeProperty this ../config }};
{{/each}}
}
handlebars
{{! 生成TypeScript接口 }}
export interface {{ toPascalCase schema.moduleName }}Input
{
{{#each (getWithoutTimestampsProperties schema.aggregateProperties)}}
    {{ toCamelCase name }}{{#if nullable}}?{{/if}}: {{ getDtoTypeProperty this ../config }};
{{/each}}
}

Example 3: Complex Import Management

示例3:复杂导入管理

handlebars
{{
    setVar 'importsArray' (
        array
            (object items=(array 'Injectable' 'Inject') path='@nestjs/common')
    )
~}}
{{#each (getEnumProperties schema.aggregateProperties)}}
{{
    push ../importsArray
        (object items=(toPascalCase name) path='@api/graphql')
~}}
{{/each}}
{{{ importManager (object imports=importsArray) }}}
handlebars
{{
    setVar 'importsArray' (
        array
            (object items=(array 'Injectable' 'Inject') path='@nestjs/common')
    )
~}}
{{#each (getEnumProperties schema.aggregateProperties)}}
{{
    push ../importsArray
        (object items=(toPascalCase name) path='@api/graphql')
~}}
{{/each}}
{{{ importManager (object imports=importsArray) }}}

Example 4: Conditional Blocks with Context

示例4:带上下文的条件块

handlebars
{{#each (getDtoProperties schema.aggregateProperties)}}
{{#if (isAllowProperty ../schema.moduleName this)}}
    {{#eq type ../propertyType.ENUM}}
        // Handle enum type
        {{ toPascalCase ../schema.moduleName }}{{ toPascalCase name }}
    {{else}}
        // Handle other types
        {{ getDtoTypeProperty this ../config }}
    {{/eq}}
{{/if}}
{{/each}}

handlebars
{{#each (getDtoProperties schema.aggregateProperties)}}
{{#if (isAllowProperty ../schema.moduleName this)}}
    {{#eq type ../propertyType.ENUM}}
        // 处理枚举类型
        {{ toPascalCase ../schema.moduleName }}{{ toPascalCase name }}
    {{else}}
        // 处理其他类型
        {{ getDtoTypeProperty this ../config }}
    {{/eq}}
{{/if}}
{{/each}}

Commands

命令

bash
undefined
bash
undefined

Build after adding helpers

添加助手后执行构建

yarn build
yarn build

Find all helpers

查找所有助手

ls src/@cliter/handlebars/helpers/
ls src/@cliter/handlebars/helpers/

Find helper usage in templates

在模板中查找助手的使用

grep -r "helperName" src/templates/
grep -r "helperName" src/templates/

Test template rendering

测试模板渲染

yarn test

---
yarn test

---

Common Mistakes to Avoid

常见错误规避

  1. Missing whitespace control: Use
    ~
    to trim unwanted whitespace
    handlebars
    {{! Bad - adds extra lines }}
    {{#if condition}}
    content
    {{/if}}
    
    {{! Good - clean output }}
    {{~#if condition}}
    content
    {{~/if}}
  2. Wrong context access: Use
    ../
    to access parent context in loops
    handlebars
    {{#each items}}
        {{ ../schema.moduleName }}  {{! Access parent, not current item }}
    {{/each}}
  3. Forgetting to register helper: Add import in
    src/@cliter/handlebars/helpers/index.ts
  4. Using
    {{
    instead of
    {{{
    : For HTML/code output, use triple braces to avoid escaping

  1. 遗漏空白字符控制:使用
    ~
    移除不必要的空白字符
    handlebars
    {{! 错误写法 - 会添加多余换行 }}
    {{#if condition}}
    content
    {{/if}}
    
    {{! 正确写法 - 输出更整洁 }}
    {{~#if condition}}
    content
    {{~/if}}
  2. 上下文访问错误:在循环中使用
    ../
    访问父上下文
    handlebars
    {{#each items}}
        {{ ../schema.moduleName }}  {{! 访问父上下文,而非当前项 }}
    {{/each}}
  3. 忘记注册助手:在
    src/@cliter/handlebars/helpers/index.ts
    中添加导入
  4. 错误使用
    {{
    而非
    {{{
    :对于HTML/代码输出,使用三重大括号避免转义

Resources

资源

  • Templates: See assets/ for helper and partial templates
  • Aurora Helpers: See references/helpers-reference.md for Aurora CLI custom helpers
  • Built-in Helpers: See references/handlebars-helpers-reference.md for handlebars-helpers package
  • GitHub: https://github.com/helpers/handlebars-helpers
  • 模板:查看assets/获取助手和片段模板
  • Aurora助手:查看references/helpers-reference.md获取Aurora CLI自定义助手文档
  • 内置助手:查看references/handlebars-helpers-reference.md获取handlebars-helpers包的完整文档
  • GitHubhttps://github.com/helpers/handlebars-helpers