基础知识
通过以下这些基础概念,你可以快速了解如何使用Handlebars helper 和 object进行主题开发。
资源 handles
代表商店资源的对象,如产品、集合、文章和博客,具有用于标识个体资源的 handle。该 handle 用于构建资源的URL,或者获取资源 object。
其他 object,如 linklists、links,同样也具有 handle。
创建和修改 handle
Handle 是基于资源标题自动生成的,并遵循一组规则:
- Handle 始终为小写。
- 空格和特殊字符被替换为连字符
-。 - 如果有多个连续的空格或特殊字符,则它们被替换为单个连字符。
- 开头的空格或特殊字符将被移除。
同一个资源下的 Handle 需要保持唯一性,因此如果使用了重复的标题,则 handle 会自动递增一。例如,如果有两个名为 "bed" 的产品,则它们的 handle 分别为 bed 和 bed-1。
创建资源后,更改资源标题不会更新 handle。
你可以在 SHOPLINE 管理后台中修改资源的 handle。在具体资源的管理页面的seo组件编辑 handle 信息。如果通过 handle 引用资源,请确保在修改 handle 时更新这些引用。
linklist 中的个别链接根据其标题生成 handle (例如 linklist.header),这些 handle 无法直接修改。
从 settings_schema.json、sections 或 blocks 中获取的个别设置使用其 id 属性作为 handle。
使用 handle
所有具有 handle 的对象都有一个 handle 属性。例如,您可以使用 product.handle 输出产品的 Handle。您可以通过两种方式在父对象内引用一个对象,这个对象是通过其 Handle 标识的:
- 方括号表示法 [ ]:接受方括号内的 handle 字符串,目前不支持变量,例如 linklists.['header']。
- 点表示法 .:接受不带方括号的 handle,例如 linklists.header。
运算符
Handlebars 支持基本的逻辑和比较运算符,可用于 if 和 unless helper。
| 运算符 | 功能 |
|---|---|
| == | 等于 |
| != | 不等于 |
| > | 大于 |
| < | 小于 |
| >= | 大于等于 |
| <= | 小于等于 |
| <= | 小于等于 |
| or | 条件A或条件B |
| and | 条件A和条件B |
| contains | 检查字符串或数组中的字符串 |
运算符执行顺序
在helper中使用多个运算符时,运算符从右到左进行评估,且无法更改此顺序。
{{#if true and false or false or true }}
This evaluates to true, since Handlebars checks like this:
true and (false or (false or true))
true and (false or true)
true and true
true
{{/if}}
如果您想在计算中使用优先级 ()。
上述用法是 helper 的内联使用。当执行到 () 时,将执行内部的 helper 表达式,获取结果,然后继续进行操作。
{{#if true and (if true and true) or false }}
This evaluates to true, since Handlebars checks like this:
true and (( true and true ) or false)
true and (true or false)
true and true
true
{{/if}}
类型
Handlebars 的输出可以是五种数据类型。
字符串(string)
任何一系列的字符,可以用单引号或双引号括起来。
您可以使用 '' 或者 "" 来检查字符串是否为空。
数字(number)
数值,包括浮点数和整数。
布尔(boolean)
二进制值,要么是 true,要么是 false。
空值(null)
未定义的值。
返回 null 的helper或输出不会在页面上打印任何内容。它们也被视为 false。
数组(array)
任何类型的变量列表。
要访问数组中的所有项,可以使用 for helper遍历数组中的每一项。
可以使用方括号 .[ ] 表示法访问数组中的特定项。数组索引从零开始。
在 Handlebars 中无法仅使用其本身初始化数组。不过,您可以使用 split 帮助程序将单个字符串拆分为子字符串数组。
真值和假值
所有数据 类型必须返回 true 或 false。默认返回 true 的被称为真值(truthy),默认返回 false 的被称为假值(falsy)。
| 值 | 真值 | 假值 |
|---|---|---|
| true | ✔️ | |
| false | ✔️ | |
| null | ✔️ | |
| 字符串 | ✔️ | |
| 空字符串 | ✔️ | |
| 0 | ✔️ | |
| 整数 | ✔️ | |
| 浮点数 | ✔️ | |
| 数组 | ✔️ | |
| 空数组 | ✔️ | |
| 页面 | ✔️ | |
| 对象 | ✔️ | |
| 空对象 | ✔️ |
例子
在 Handlebars 中检查值时需要小心。一个值可能不是您预期的格式,但仍然可能是真值。
<!-- It is true if settings.product.collections is an empty array, so you need to use the length to determine whether there are collections. -->
{{#if settings.product.collections.size != 0}}
{{ settings.product.handle }}
{{else}}
No value for this setting has been selected.
{{/if}}
空白符控制
可以通过在花括号旁边添加一个 ~ 字符来省略模板中任何Handlebars语句的两 侧空格/换行符/制表符等空白符。应用后,该侧的所有空白符将被删除,直到第一个Handlebars表达式或该侧的非空白符为止。
start
{{~ settings.product.title ~}}
end