【问题标题】:Loop trough collections of products循环浏览产品集合
【发布时间】:2019-03-05 13:05:57
【问题描述】:

我正在尝试遍历一组产品所属的所有集合。这是我的代码:

<div class="container model-collection">
<h1>{{ collection.title }}</h1>
{% paginate collection.products by 12 %}
  <div class="grid collection-products-container">
    <ul>
    {% for product in collection.products %}
    {% for collection in product.collections %}
  <li><a href="{{ collection.url }}">{{ collection.title }}</a></li>
{% endfor %}
    {% endfor %}
  </ul>
</div>
  {% if paginate.pages > 1 %}
    {% include 'pagination' %}
  {% endif %}
{% endpaginate %}
</div>

这很好用,但是如果两个产品属于同一个集合,它会列出该集合两次。所以我需要限制它只显示每个集合一次的循环。 我试过这样做:

<div class="container model-collection">
<h1>{{ collection.title }}</h1>
{% assign model = collection.title %}
  <div class="grid collection-products-container">
    <ul>
    {% for product in collection.products %}
    {% assign seen_collections = "" %}
    {% for collection in product.collections %}
{% unless seen_collections contains collection %}
{% assign seen_collections = seen_collections | append: "," | append: collection  %}
  <li><a href="{{ collection.url }}/{{ model }}">{{ collection.title }}</a></li>
  {% endunless %}
{% endfor %}
    {% endfor %}
  </ul>
</div>
</div>

但这只会返回其中一个集合两次,而不会返回其他集合。任何想法如何做到这一点?

【问题讨论】:

    标签: html shopify


    【解决方案1】:

    您可以通过在 Liquid 代码中使用 map 过滤器来获取嵌套属性的聚合列表,而 map 过滤器可以让您非常有效地钻入嵌套对象。

    因此,要获取集合中所有产品使用的所有唯一集合句柄的数组,我们可以快速获取我们想要的信息:

    {% assign collection_handles = collection.products | map: 'collections'  | map: 'handle' | uniq %}
    

    这将创建集合中所有产品的所有集合句柄的数组,然后将它们减少为唯一的句柄(使用uniq 过滤器)。注意:uniq 需要使用数字、字符串或其他简单字段 - 这就是我们需要集合句柄数组而不是集合对象数组的原因。

    所以现在你可以这样循环:

    {% for handle in collection_handles %}
      {% assign collection = collections[handle] %}
      <!-- All your awesome stuff here -->
    {% endfor %}
    

    希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-02-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-20
      • 1970-01-01
      • 2022-11-23
      相关资源
      最近更新 更多