模板
模板标签告诉 Liquid 在何处禁用注释或非 Liquid 标记的处理,以及如何在模板文件之间建立关系。
comment
允许你在 Liquid 模板中保留未渲染的代码。任何在 comment
标签块内的文本都不会被打印,并且其中的任何 Liquid 代码都不会被执行。
输入
{% assign verb = "turned" %}
{% comment %}
{% assign verb = "converted" %}
{% endcomment %}
Anything you put between {% comment %} and {% endcomment %} tags
is {{ verb }} into a comment.
输出
Anything you put between tags
is turned into a comment.
内联注释
你可以使用内联注释来阻止表达式被渲染或输出。标签内的任何文本也不会被渲染或输出。
你可以创建多行内联注释。但是,每一行都必须以 #
开头。
输入
{% # for i in (1..3) -%}
{{ i }}
{% # endfor %}
{%
###############################
# This is a comment
# across multiple lines
###############################
%}
输出
liquid
标签内的内联注释
你可以在 liquid
标签内使用内联注释标签。该标签必须用于你想注释的每一行。
输入
{% liquid
# this is a comment
assign topic = 'Learning about comments!'
echo topic
%}
输出
Learning about comments!
raw
临时禁用标签处理。这对于生成使用冲突语法的特定内容(例如 Mustache 或 Handlebars)非常有用。
输入
{% raw %}
In Handlebars, {{ this }} will be HTML-escaped, but {{{ that }}} will not.
{% endraw %}
输出
In Handlebars, {{ this }} will be HTML-escaped, but {{{ that }}} will not.
liquid
将多个标签括在一组分隔符中,以便更简洁地编写 Liquid 逻辑。
{% liquid
case section.blocks.size
when 1
assign column_size = ''
when 2
assign column_size = 'one-half'
when 3
assign column_size = 'one-third'
else
assign column_size = 'one-quarter'
endcase %}
因为在 liquid
标签内打开的任何标签块也必须在同一标签内关闭,所以请使用 echo
来输出数据。
echo
在渲染的 HTML 中输出一个表达式。这与将表达式包裹在 {{
和 }}
中相同,但可以在 liquid
标签内工作,并支持过滤器。
输入
{% liquid
for product in collection.products
echo product.title | capitalize
endfor %}
输出
Hat Shirt Pants
render
在当前模板中插入另一个模板的渲染内容。
{% render "template-name" %}
请注意,你不需要写文件的 .liquid
扩展名。
渲染的模板中的代码 不 会自动访问在父模板中使用变量标签分配的变量。同样,在渲染的模板中分配的变量也不能被任何其他模板中的代码访问。
render (参数)
可以使用render
标签将使用变量标签分配的变量作为参数传递给模板。
{% assign my_variable = "apples" %}
{% render "name", my_variable: my_variable, my_other_variable: "oranges" %}
可以将一个或多个对象传递给模板。
{% assign featured_product = all_products["product_handle"] %}
{% render "product", product: featured_product %}
with
可以使用 with
和可选的 as
参数将单个对象传递给模板。
{% assign featured_product = all_products["product_handle"] %}
{% render "product" with featured_product as product %}
在上面的示例中,渲染的模板中的 product
变量将保存父模板中 featured_product
的值。
for
可以使用 for
和可选的 as
参数为可枚举对象的每个值渲染一次模板。
{% assign variants = product.variants %}
{% render "product_variant" for variants as variant %}
在上面的示例中,该模板将为产品的每个变体渲染一次,并且 variant
变量将在每次迭代中保存不同的产品变体对象。
当使用 for
参数时,可以在渲染的模板中访问 forloop
对象。
include
include
标签已被弃用;请改用 render
。
在当前模板中插入另一个模板的渲染内容。
{% include "template-name" %}
include
标签的工作方式类似于 render
标签,但它允许渲染的模板内的代码访问和覆盖其父模板中的变量。它已被弃用,因为它处理变量的方式会降低性能,并使 Liquid 代码更难阅读和维护。
请注意,当使用 render
标签渲染模板时,不能在模板内使用 include
标签。