# 内置助手

¥Built-in Helpers

# #if

你可以使用 if 助手有条件地渲染块。如果其参数返回 falseundefinednull""0[],Handlebars 将不会渲染该块。

¥You can use the if helper to conditionally render a block. If its argument returns false, undefined, null, "", 0, or [], Handlebars will not render the block.

template
<div class="entry">
{{#if author}}
<h1>{{firstName}} {{lastName}}</h1>
{{/if}}
</div>

当你将以下输入传递给上面的模板时

¥When you pass the following input to the above template

input
{
  author: true,
  firstName: "Yehuda",
  lastName: "Katz",
}

这将产生如下结果:

¥This will produce the result as below:

output
<div class="entry">
<h1>Yehuda Katz</h1>
</div>

如果输入是空的 JSONObject {},则 author 将变为 undefined,并且 if 条件失败,导致输出如下:

¥If the input is an empty JSONObject {}, then author will become undefined and if condition fails, resulting in the output as follow:

<div class="entry"></div>

使用块表达式时,你可以指定在表达式返回假值时要运行的模板部分。标有 else 的部分称为 "其他部分"。

¥When using a block expression, you can specify a template section to run if the expression returns a falsy value. The section, marked by else is called an "else section".

template
<div class="entry">
{{#if author}}
<h1>{{firstName}} {{lastName}}</h1>
{{else}}
<h1>Unknown Author</h1>
{{/if}}
</div>

# includeZero

可以设置 includeZero=true 选项以将条件视为非空。这有效地确定了 0 是由正路径还是负路径处理。

¥The includeZero=true option may be set to treat the conditional as not empty. This effectively determines if 0 is handled by the positive or negative path.

{{#if 0 includeZero=true}}
<h1>Does render</h1>
{{/if}}

# 子表达式

¥Sub-Expressions

助手是向模板添加自定义逻辑的建议方法。你可以编写任何辅助程序并在子表达式中使用它。

¥Helpers are the proposed way to add custom logic to templates. You can write any helper and use it in a sub-expression.

例如,在检查变量的初始化时,内置 #if 检查可能不合适,因为它对于空集合返回 false(请参阅 Utils.isEmpty)。

¥For example, in checking for initialization of a variable the built-in #if check might not be appropriate as it returns false for empty collections (see Utils.isEmpty).

你可以编写一个检查 "undefined" 的辅助程序,例如:

¥You could write a helper that checks for "undefined" such as:

preparationScript
Handlebars.registerHelper('isdefined', function (value) {
  return value !== undefined;
});

然后使用你的助手作为子表达式:

¥Then use your helper as a sub-expression:

template
{{#if (isdefined value1)}}true{{else}}false{{/if}}
{{#if (isdefined value2)}}true{{else}}false{{/if}}

# #unless

你可以使用 unless 辅助函数作为 if 辅助函数的逆函数。如果表达式返回一个假值,它的块将被渲染。

¥You can use the unless helper as the inverse of the if helper. Its block will be rendered if the expression returns a falsy value.

template
<div class="entry">
{{#unless license}}
<h3 class="warning">WARNING: This entry does not have a license!</h3>
{{/unless}}
</div>

如果在当前上下文中查找 license 返回一个假值,Handlebars 将渲染警告。否则,它不会渲染任何内容。

¥If looking up license under the current context returns a falsy value, Handlebars will render the warning. Otherwise, it will render nothing.

# #each

你可以使用内置的 each 辅助程序迭代列表。在块内,你可以使用 this 来引用正在迭代的元素。

¥You can iterate over a list using the built-in each helper. Inside the block, you can use this to reference the element being iterated over.

template
<ul class="people_list">
  {{#each people}}
    <li>{{this}}</li>
  {{/each}}
</ul>

当与此上下文一起使用时:

¥when used with this context:

input
{
  people: [
    "Yehuda Katz",
    "Alan Johnson",
    "Charles Jolley",
  ],
}

将导致:

¥will result in:

output
<ul class="people_list">
    <li>Yehuda Katz</li>
    <li>Alan Johnson</li>
    <li>Charles Jolley</li>
</ul>

你可以在任何上下文中使用 this 表达式来引用当前上下文。

¥You can use the this expression in any context to reference the current context.

你可以选择提供 else 部分,该部分仅在列表为空时显示。

¥You can optionally provide an else section which will display only when the list is empty.

template
{{#each paragraphs}}
<p>{{this}}</p>
{{else}}
<p class="empty">No content</p>
{{/each}}

当循环 each 中的项目时,你可以选择通过 {{@index}} 引用当前循环索引。

¥When looping through items in each, you can optionally reference the current loop index via {{@index}}.

{{#each array}} {{@index}}: {{this}} {{/each}}

此外,对于对象迭代,{{@key}} 引用当前键名称:

¥Additionally for object iteration, {{@key}} references the current key name:

{{#each object}} {{@key}}: {{this}} {{/each}}

迭代数组时,迭代的第一步和最后一步通过 @first@last 变量来记录。

¥The first and last steps of iteration are noted via the @first and @last variables when iterating over an array.

嵌套的 each 块可以通过基于深度的路径访问迭代变量。例如,要访问父索引,可以使用 {{@../index}}

¥Nested each blocks may access the iteration variables via depth based paths. To access the parent index, for example, {{@../index}} can be used.

# #with

with 辅助程序允许你更改模板部分的评估上下文。

¥The with-helper allows you to change the evaluation context of template-part.

template
{{#with person}}
{{firstname}} {{lastname}}
{{/with}}

当与此上下文一起使用时:

¥when used with this context:

input
{
  person: {
    firstname: "Yehuda",
    lastname: "Katz",
  },
}

将导致:

¥will result in:

output
Yehuda Katz

with 还可以与块参数一起使用来定义当前块中的已知引用。上面的例子可以转换为

¥with can also be used with block parameters to define known references in the current block. The example above can be converted to

template
{{#with city as | city |}}
  {{#with city.location as | loc |}}
    {{city.name}}: {{loc.north}} {{loc.east}}
  {{/with}}
{{/with}}

这使得复杂的模板有可能提供比 ../ 深度引用更清晰的代码。

¥Which allows for complex templates to potentially provide clearer code than ../ depthed references allow for.

你可以选择提供 {{else}} 部分,该部分仅在传递的值为空时显示。

¥You can optionally provide an {{else}} section which will display only when the passed value is empty.

template
{{#with city}}
{{city.name}} (not shown because there is no city)
{{else}}
No city found
{{/with}}
input
{
  person: {
    firstname: "Yehuda",
    lastname: "Katz",
  },
}

# lookup

lookup 辅助程序允许使用 Handlebars 变量进行动态参数解析。

¥The lookup helper allows for dynamic parameter resolution using Handlebars variables.

这对于解析数组索引的值很有用。

¥This is useful for resolving values for array indexes.

template
{{#each people}}
   {{.}} lives in {{lookup ../cities @index}}
{{/each}}

它还可用于根据输入数据查找对象的属性。以下是一个更复杂的示例,它在子表达式中使用 lookup 根据属性值将求值上下文更改为另一个对象。

¥It can also be used to lookup properties of object based on data from the input. The following is a more complex example that uses lookup in a sub-expression to change the evaluation context to another object based on a property-value.

template
{{#each persons as | person |}}
    {{name}} lives in {{#with (lookup ../cities [resident-in])~}}
      {{name}} ({{country}})
    {{/with}}
{{/each}}

# log

log 辅助程序允许在执行模板时记录上下文状态。

¥The log helper allows for logging of context state while executing a template.

template
{{log 'this is a simple log output'}}

它委托给 Handlebars.logger.log,可以覆盖该 Handlebars.logger.log 以执行自定义日志记录。

¥It delegates to Handlebars.logger.log which may be overridden to perform custom logging.

可以将任意数量的参数传递给此方法,并且所有参数都将转发到日志器。

¥Any number of arguments may be passed to this method and all will be forwarded to the logger.

template
{{log 'firstname' firstname 'lastname' lastname}}

可以使用级别散列参数来设置日志级别。支持的值为 debug、info、warn 和 error。省略时,info 为默认值,

¥The log level may be set using the level hash parameter. Supported values are debug, info, warn, and error. When omitted, info is the default value,

日志记录是有条件的,基于 Handlebars.logger.level 中设置的级别和值,默认为 info。所有等于或高于当前级别的日志语句都会被输出。

¥Logging is conditional based on the level and to value set in Handlebars.logger.level, which defaults to info. All log statements at or above the current level will be output.

template
{{log "debug logging" level="debug"}}
{{log "info logging" level="info"}}
{{log "info logging is the default"}}
{{log "logging a warning" level="warn"}}
{{log "logging an error" level="error"}}
Last Updated: 2024/4/16 21:37:19