液体模板:for循环中的偶数/奇数项

Ada*_*iss 46 liquid jekyll

如果我在Liquid中有一个for循环(使用Jekyll),我怎么能只针对偶数(或奇数)项?我试过了:

{% for item in site.posts %}
    {% if forloop.index % 2 == 1 %}
Run Code Online (Sandbox Code Playgroud)

但这似乎不起作用.我也尝试过:

(forloop.index % 2) == 1
Run Code Online (Sandbox Code Playgroud)

和:

forloop.index - (forloop.index / 2 * 2) == 1
Run Code Online (Sandbox Code Playgroud)

Ale*_*nde 69

我想你会想要使用循环标签.例如:

{% for post in site.categories.articles %}
   <article class="{% cycle 'odd', 'even' %}"></article>
{% endfor %}
Run Code Online (Sandbox Code Playgroud)

如果您希望每个周期使用不同的HTML标记:

{% for item in site.posts %}
  {% capture thecycle %}{% cycle 'odd', 'even' %}{% endcapture %}
  {% if thecycle == 'odd' %}
    <div>echo something</div>
  {% endif %}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)

你可以在Liquid for Designers找到更多关于它的信息,尽管那里的例子没有特别的帮助.这个Shopify支持线程也应该有所帮助.

  • 这并不是我要找的东西,但是您找到的链接为我提供了真正的答案。我编辑了您的答案以包括我的解决方案。谢谢! (2认同)

Chr*_*cht 24

与此相反,以什么Shopify支持线程强麦揽得的回答说,有一个modulo在液相功能-在形式modulo过滤器.

有了它,你可以这样做:

{% for item in site.posts %}
    {% assign mod = forloop.index | modulo: 2 %}
    {% if mod == 0 %}
        <!-- even -->
    {% else %}
        <!-- odd -->
    {% endif %}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)

  • 我比使用`cycle`的解决方案更喜欢这个解决方案; 使用字符串解决数学问题似乎......奇怪! (3认同)