1

我正在使用 a为系统中存在的每个博客文章for loop生成。cards

生成的卡片将具有不同的宽度。一张卡片可以是large或者small为了实现这一点,我正在使用 HubL 的cycle语法(此处的文档)。我试图实现的卡片宽度的视觉示例可以在这里看到:

在此处输入图像描述

现在,第一行中的第三张卡片将不再是 for 循环的一部分,例如,它将是一张图片。

在此处输入图像描述

我遇到的问题:

  • 卡片 1 和 2 显示最新帖子(如预期)
  • 然后,for 循环停止,所以我可以得到浅蓝色卡(因为Twig也不HubL支持break语法。
  • 在我已经说过之后,我开始了另一个循环{% if loop.index >=3 %}- 所以跳过循环中的前两个项目,因为最新的卡片显示在第一个循环中。但是,在cycle我已经定义的情况下,它会显示错误的卡片类。下面的代码示例:

.container{
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}

.card{
  margin-bottom: 15px;
  border: 1px solid;
  padding: 20px;
}

.card--large{
  width: 40%;
}

.card--small{
  width: 20%;
}

.card--filler{
  width: 20%;
  background: lightblue;
}
<div class="container">

  <!-- first loop will get two latest cards, first card will be card--large, second card--small -->
  {% for content in contents %}
    {% if loop.index <=2 %}
      <div class="card {% cycle 'card--large','card--small' %}">
        Test
      </div>
    {% endif %}
  {% endif %}
  
  <!-- this is outside the loop -->
  <div class="card card--filler">
    This card is not part of the for loop
  </div>
  
  
  <!-- defining new loop where first two entries should be skipped -->
  {% for content in contents %}
    {% if loop.index >=3 %}
    <div class="card {% cycle 'card--small','card--small','card--large','card--large','card--small','card--small' %}">
      Test
    </div>
    {% endif %}
  {% endfor %}
  

</div>

在上面的最后一个循环中,由于我忽略了前两个帖子,因此它也忽略了cycle参数中的前两个项目。无论循环如何,卡片都应具有以下类:

  • 第一张卡片:卡片--小
  • 第二张牌:card--small
  • 第三张牌:card--large
  • 第四张牌:card--large
  • 第五张牌:卡片——小
  • 第六张卡片:卡片--小
  • 然后它将再次从顶部开始

但是,正在发生的事情是:

  • 第一张卡片:卡片--大
  • 第二张牌:card--large
  • 第三张卡片:卡片——小
  • 第四张卡片:卡片——小
  • ...

我也尝试过{% if not loop.second %}{% if loop.index >=3 %}但它只是再次获得相同的帖子,例如:

在此处输入图像描述

4

2 回答 2

1

您可以设置一个序列数组并将其与循环函数一起使用以循环遍历类序列,因为对于第一个循环,您可以使用slice() 过滤器在第二个元素之后执行部分,或者您也可以使用语法糖[start:length]

container.twig
{% set sequence = ['small','small','large','large','small','small'] %}

<div class="container">

  {% for content in contents[0:3] %}
      {% include 'card.twig' with { card: cycle(sequence[3:], loop.index0) } %}
  {% endfor %}
  
  <div class="card card--filler">
    This card is not part of the for loop
  </div>
  
  {% for content in contents[3:] %}
      {% include 'card.twig' with { card: cycle(sequence, loop.index0) } %}
  {% endfor %}
</div>

工作示例

于 2020-07-17T14:32:34.590 回答
0

为什么不放开循环并在循环中创建一个不会破坏循环但会显示其他内容的 if?

请注意,顺便说一下, Twig 中也存在cycle它,它根据当前循环索引给出循环值,因此,让你的循环运行,即使你的“例外卡”也可以解决你的问题。

<div class="container">
  {% for content in contents %}
    <div class="card {% cycle 'card--large','card--small','card--small','card--small','card--large'">
      Test
    </div>
    {% if loop.index == 2  }
      <!-- this is outside the loop -->
      <div class="card card--filler">
        This card is not part of the for loop
      </div>
    {% endif %}
  {% endif %}
</div>
于 2020-07-11T19:01:21.327 回答