Liquid:能否在for循环语句中赋值并使用变量?
在Liquid的for循环中动态赋值并调用集合的解决方案
当然可以在Liquid里实现这种动态渲染产品集合的需求!你的思路完全可行——通过文章标签传递集合句柄,不用为每篇文章重复编写for循环。下面给你具体的实现步骤和代码示例:
步骤1:从文章标签中提取集合句柄
首先我们要从文章的标签里筛选出以collection_开头的标签,再去掉前缀拿到集合的真实句柄:
{% comment %} 筛选出带collection_前缀的目标标签 {% endcomment %} {% assign collection_tag = article.tags | where_exp: "tag", "tag contains 'collection_'" | first %} {% comment %} 若找到对应标签,提取出集合句柄 {% endcomment %} {% if collection_tag %} {% assign target_collection_handle = collection_tag | remove: 'collection_' %} {% endif %}
步骤2:动态获取目标集合
Liquid支持用方括号语法通过变量引用集合,这是实现动态调用的关键:
{% if target_collection_handle %} {% assign target_collection = collections[target_collection_handle] %} {% endif %}
步骤3:用动态集合渲染产品列表
现在你就能像使用普通集合一样,在for循环里直接用这个动态获取的集合了:
{% if target_collection %} <h2>相关产品集合</h2> <div class="product-list"> {% for product in target_collection.products limit: 6 %} <div class="product-item"> <a href="{{ product.url }}"> <img src="{{ product.featured_image | img_url: '250x250' }}" alt="{{ product.title }}"> <h3>{{ product.title }}</h3> <span>{{ product.price | money }}</span> </a> </div> {% endfor %} </div> {% else %} <p>暂无相关产品集合展示</p> {% endif %}
实用注意事项
- 标签命名要严谨:确保标签严格遵循
collection_集合句柄的格式,比如集合句柄是winter-collection,标签就要写collection_winter-collection,避免空格或特殊字符导致匹配失败。 - 容错处理不能少:一定要加
if判断(比如if target_collection),防止因为标签错误或集合不存在导致页面渲染异常。 - 变量作用域说明:Liquid中在循环外赋值的变量,循环内可以直接使用;如果在循环内赋值新变量,也能正常使用,但不会影响循环外的同名变量(块级作用域特性)。
内容的提问来源于stack exchange,提问作者Dustin Lee
相关产品推荐
相关产品推荐

