【问题标题】:Liquid | Jekyll - For loop with 2 conditions and with limit?液体 | Jekyll - 有 2 个条件和限制的 For 循环?
【发布时间】:2016-04-14 22:30:35
【问题描述】:

我想从属于两个(或多个)不同类别的帖子列表中获取第一个 post.content。

以下确实有效,但不排除除第一个结果之外的所有结果:

{% for post in site.categories.categorie_A and for post in site.categories.categorie_B %}
    {{ post.content }}
{% endfor %}

对此设置限制,将一无所获(虽然它应该有效):

{% for post in site.categories.categorie_A and for post in site.categories.categorie_B limit:1 %}
    {{ post.content }}
{% endfor %}

这也不起作用:

{% for post in site.categories.categorie_A limit:1 and for post in site.categories.categorie_B limit:1 %}
    {{ post.content }}
{% endfor %}

即使是 if 语句也无法完成这项工作:

{% for post in site.categories.categorie_A and for post in site.categories.categorie_B %}
    {% if forloop.first == true %}
          {{ post.content }}
    {% endif %}
{% endfor %}

以及嵌套的 for 循环:

{% for post in site.categories.categorie_A %}
    {% for categorie_A_post in post.categories.categorie_B %}
        {{ categorie_A_post.content }}
    {% endfor %}
{% endfor %}

【问题讨论】:

    标签: jekyll liquid


    【解决方案1】:

    或者类似的东西:

    {% for p in site.posts %}
      {% if p.categories contains "categorie_A" and p.categories contains "categorie_B" %}
        <p>{{ p.title }}</p>
        {% break %}{% comment %}Exit the loop{% endcomment %}
      {% endif %}
    {% endfor %}
    

    【讨论】:

    • 非常好,我想知道中断在液体中是如何工作的,我认为将类别嵌套在 (if's) 中是更干净的方式,按照我在液体上阅读的所有内容
    【解决方案2】:

    我发现这行得通,不是很漂亮,但它行得通。

              {% for post in site.posts %}
                  {% if post.categories contains "categorie_A" and post.categories contains "categorie_B" %}
                      {% capture times_if %}{% increment times_if %}{% endcapture %}
                      {% if times_if == '0' %}
                          {{ post.content }}
                      {% endif %}
                  {% endif %}
              {% endfor %}
    

    还有一点简洁(没有“和”)

    {% for post in site.posts %}
        {% if post.categories contains "categorie_A" %}
            {% if post.categories contains "categorie_B" %}
                {% capture times_if %}{% increment times_if %}{% endcapture %}
                {% if times_if == '0' %}
                    {{ post.content }}
                {% endif %}
            {% endif %}
        {% endif %}
    {% endfor %}
    

    【讨论】:

      【解决方案3】:

      也可以使用 forloop 变量来编写。如果您想要第二个或第三个结果,forloop 变量也可以工作:

      {% for post in site.posts %}
        {% if post.categories contains "categorie_A" and post.categories contains "categorie_B" %}
          {% if forloop.first == true %}
            {{ post.content }}
          {% endif %}
        {% endif %}
      {% endfor %}
      

      了解有关此变量here 的更多信息。祝你好运!

      【讨论】:

        猜你喜欢
        • 2018-11-01
        • 2017-12-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-12-28
        • 1970-01-01
        相关资源
        最近更新 更多