javascript - 在 Liquid 中的集合页面中,每隔 n 次迭代渲染一次
问题描述
如何添加不同的列表项,例如在派生自的第三个、第七个和第十一个列表项之后显示图像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>
解决方案
我不知道您要添加什么 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>
您还可以使用一个模过滤器,但是对于像第 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>
推荐阅读
- java - 如何从该 svg 标签中抓取数据
- azure - 更新 azure devops 发布管道:版本为“部署平台 3:1.*”的任务对于部署作业“在代理上运行”无效
- javascript - 如何在提供的 lat/lng 对数组之间获取所有 lat/lng 对的数组
- node.js - Nodejs等待多个数据库调用
- javascript - 在 Google 表格中,如何更改用户看到的表格?
- amazon-web-services - 将 EC2 实例备份到外部硬盘
- ios - iOS 自动布局 - 当您想让视图拉伸到其父级的完整大小时,正确的方法是什么?
- node.js - 部署到 Heroku 时出现内部服务器错误
- sql - 在 SQL 语句中使用 OR
- php - 对表格输出的循环进行分页