在 For 循环 Liquid 中添加一个变量

Adding a Variable in For Loop Liquid

是否可以分配一个变量并在 for 循环语句中使用该变量?

我正在尝试在博客中放置产品集合,而不必为需要集合的每篇文章创建新的 for 循环。

我所做的是使用文章的标签并在集合句柄之前拆分,这样我就可以将它注入 for 循环,但它还不能完全动态地工作...

这是我所做的..我在文章标签中添加了

collection_some-page-handle
然后在 article.liquid

    {% for tag in article.tags %}

      {% assign tagMap = tag | split: '_' %}
      {% if tagMap.first == 'collection' %}
        {% assign collectionName = tagMap.last %}
      {% endif %}
    {% endfor %}
    {{collectionName}} <!-- this shows the handle of the collection -->
    {% for product in collections.collectionName.products limit: 8%}
    <div class="productWrap">
            <a href="{{ product.url}}"><img src="{{ product.featured_image | product_img_url: 'medium' }}" alt=""></a>
          <a href="{{product.url}}"><p class="product_title" style="border-top:1px solid #efefef;">{{ product.title | split: ' - ' | first }}</p></a>
    </div>
    {%endfor%}

现在,如果我尝试将变量放入 for 循环中,它不起作用,但当然,如果我放入实际句柄,它就会起作用。有没有办法动态地做到这一点?

而不是使用 collections.collectionName 使用 collections[collectionName].

如果您的变量确实具有正确的句柄,这应该可以解决您的问题。

为了澄清您何时使用 collections.collectionName,您说 - “给我一个具有 handle collectionName 的集合。

当你使用 collections[collectionName] 时你说 - "Get me a collection using the variable collectionName as a handle."