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

发布于 2024-12-28 22:57:36 字数 314 浏览 4 评论 0 原文

如果我在 Liquid 中有一个 for 循环(使用 Jekyll),我如何才能只定位偶数(或奇数)项?我已经尝试过:

{% for item in site.posts %}
    {% if forloop.index % 2 == 1 %}

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

(forloop.index % 2) == 1

和:

forloop.index - (forloop.index / 2 * 2) == 1

If I have a for loop in Liquid (using Jekyll), how can I target even (or odd) items only? I have tried:

{% for item in site.posts %}
    {% if forloop.index % 2 == 1 %}

but that doesn't seem to work. I have also tried:

(forloop.index % 2) == 1

and:

forloop.index - (forloop.index / 2 * 2) == 1

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

薯片软お妹 2025-01-04 22:57:36

我想你会想为此使用循环标签。例如:

{% for post in site.categories.articles %}
   <article class="{% cycle 'odd', 'even' %}"></article>
{% endfor %}

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

{% for item in site.posts %}
  {% capture thecycle %}{% cycle 'odd', 'even' %}{% endcapture %}
  {% if thecycle == 'odd' %}
    <div>echo something</div>
  {% endif %}
{% endfor %}

您可以在 Liquid for Designers,尽管那里的示例并不是特别有帮助。此 Shopify 支持线程也应该有所帮助。

I think you'll want to use the cycle tag for this. For example:

{% for post in site.categories.articles %}
   <article class="{% cycle 'odd', 'even' %}"></article>
{% endfor %}

If you want different HTML markup for each cycle:

{% for item in site.posts %}
  {% capture thecycle %}{% cycle 'odd', 'even' %}{% endcapture %}
  {% if thecycle == 'odd' %}
    <div>echo something</div>
  {% endif %}
{% endfor %}

You can find more information on it at Liquid for Designers, although the example there isn't particularly helpful. This Shopify support thread should also help.

爱*していゐ 2025-01-04 22:57:36

Shopify 支持线程相反/stackoverflow.com/a/8980590/6884">Ales Lande 的回答说,Liquid中有一个modulo函数 - 形式为modulo 过滤器

有了它,您可以执行以下操作:

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

In contrast to what the Shopify support thread in Ales Lande's answer says, there is a modulo function in Liquid - in form of the modulo filter.

With it, you can do this:

{% for item in site.posts %}
    {% assign mod = forloop.index | modulo: 2 %}
    {% if mod == 0 %}
        <!-- even -->
    {% else %}
        <!-- odd -->
    {% endif %}
{% endfor %}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文