【问题标题】:Render something every nth iteration inside a collection page in liquid在 Liquid 中的集合页面中,每隔 n 次迭代渲染一次
【发布时间】:2021-10-28 18:52:39
【问题描述】:

如何添加不同的列表项,例如第三,第七和第十一个列表项之后的图像,源自collection.products? 我尝试过 jQuery,但它没有用。有什么想法吗?

<ul id="collection-grid" data-id="{{ section.id }}" class="grid">
  {%- for product in collection.products -%}
    <li class="grid-item">
      {% render 'product-wrapper' %}
     </li>
  {%- endfor -%}
 </ul>

<script>
   $( "ul:nth-child(3)" ).append( "<li class="info-card card-wrapper"><img...></li>" );
</script>

【问题讨论】:

    标签: javascript jquery css-selectors append liquid


    【解决方案1】:

    我不知道您要添加什么 HTML 以及在哪里添加,但我在下面做了一个猜测。

    在变量中使用cycle 标记和capture 它,然后使用if 显示您想要的内容。

    (不需要 jQuery)

    <ul id="collection-grid" data-id="{{ section.id }}" class="grid">
        {%- for product in collection.products -%}
            {% capture thisIteration %}{% cycle '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12' %}{% endcapture %}
    
            <li class="grid-item">
                {% render 'product-wrapper' %}
                {% if thisIteration == '3' %}
                    <span>Here is the HTML that is added only on every 3rd iteration</span>
                {% endif %}
                {% if thisIteration == '7' %}
                    <span>Here is the HTML that is added only on every 7th iteration</span>
                {% endif %}
                {% if thisIteration == '11' %}
                    <span>Here is the HTML that is added only on every 11th iteration</span>
                {% endif %}
            </li>
        {%- endfor -%}
    </ul>
    

    还有一个 modulo filter 可以使用,但对于第 7 和第 11 等迭代,我觉得上面的内容更具可读性。

    <ul id="collection-grid" data-id="{{ section.id }}" class="grid">
        {%- for product in collection.products -%}
            {% assign mod3 = forloop.index | modulo: 3 %}
            {% assign mod7 = forloop.index | modulo: 7 %}
            {% assign mod11 = forloop.index | modulo: 11 %}
    
            <li class="grid-item">
                {% render 'product-wrapper' %}
                {% if mod3 == 0 %}
                    <span>Here is the HTML that is added only on every 3rd iteration</span>
                {% endif %}
                {% if mod7 == 0 %}
                    <span>Here is the HTML that is added only on every 7th iteration</span>
                {% endif %}
                {% if mod11 == 0 %}
                    <span>Here is the HTML that is added only on every 11th iteration</span>
                {% endif %}
            </li>
        {%- endfor -%}
    </ul>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-03
      • 1970-01-01
      • 2022-11-14
      • 1970-01-01
      • 1970-01-01
      • 2017-08-22
      • 2018-01-19
      • 1970-01-01
      相关资源
      最近更新 更多