代码片段
Snippet 是包含小段可复用代码的 Liquid 文件。你可以在 layout、template 和 section 中引用 snippet,避免在主题中重复编写相同的代码。
Snippet 存储在主题的 snippets 目录中。
文件位置
└── theme
...
├── snippets
| ├── product-card.liquid
| ├── navigation.liquid
| ...
...
用法
引入 snippet
使用 Liquid include 标签在其他 Liquid 文件中渲染 snippet:
{% include 'my-custom-snippet' %}
也可以使用 render 标签,它会在隔离的作用域中渲染 snippet:
{% render 'my-custom-snippet' %}
传递参数
你可以在引入 snippet 时传递变量作为参数,参数在 snippet 内部作为局部变量使用。
例如,创建一个 product-card.liquid snippet:
<div class="product-card">
<h2>{{ product.title }}</h2>
<p>{{ product.description }}</p>
</div>
然后在 template 中引入并传入商品对象:
{% include 'product-card', product: featured_product %}
在 snippet 内部,product 指向从 template 传入的 featured_product 对象。{{ product.title }} 输出该商品的标题,{{ product.description }} 输出其描述。
Snippet 与 Section 的区别
Snippet 和 Section 都能实现代码复用,但用途不同:
| Snippet | Section | |
|---|---|---|
| 商家可配置设置项 | 否 | 是(通过 {% schema %}) |
| 可捆绑 CSS/JS | 否 | 是(通过 {% stylesheet %} / {% javascript %}) |
| 在主题编辑器中可见 | 否 | 是 |
| 典型用途 | 共享的标记片段(卡片、图标、分页) | 可自定义的页面模块(横幅、商品网格) |
需要纯代码复用时使用 snippet;需要商家通过主题编辑器自定义内容时使用 section。