【问题标题】:Looping in liquid and doing something every x loops在液体中循环并每 x 循环做一些事情
【发布时间】:2018-01-26 21:40:10
【问题描述】:

我正在使用液体模板,我想遍历一个数组,并吐出一些看起来像这样的 HTML,

    <div class="classname">
        <div>
          <a>1</a>
          <a>2</a>
          <a>3</a>
          <a>4</a>
          <a>5</a>
          <a>6</a>
        </div>
    </div>
     <div class="classname">
        <div>
          <a>7</a>
          <a>8</a>
          <a>9</a>
          <a>10</a>
          <a>11/a>
          <a>12</a>
        </div>
    </div>
    <div class="classname">
        <div>
          <a>13</a>
          <a>14</a>
          <a>15</a>
          <a>16</a>
          <a>17/a>
          <a>18</a>
        </div>
    </div>

所以基本上对于每 6 个循环,我想打开 2 个新 div 并关闭前 2 个。我已经尝试过了,这是我的努力。

{% for block in content_blocks %}
            {% assign mod = forloop.index | modulo: 6 %}
              {% if mod / 6 == 1 %}
                <div class="grid-slide">
                    <div>
            {% endif %}
                        <a href="{{block.content_block_url}}" class="location-link">
                            <img src="{{block.content_block_image | url_for_generic_image}}" />
                        </a>
            {% if mod / 6 == 1 %}
                    </div>
                </div>
            {% endif %}
        {% endfor %}

【问题讨论】:

    标签: liquid


    【解决方案1】:

    你可以用这个液体代码来实现它:

    {% assign content_blocks_length = content_blocks | size %}
    {% for block in content_blocks %}
        {% assign mod = forloop.index | modulo: 6 %}
        {% if mod  == 1 and  forloop.index != 1 %}
            </div>
            </div>
        {% endif %}
          {% if mod  == 1 %}
            <div class="grid-slide">
                <div>
        {% endif %}
            <a href="{{block.content_block_url}}" class="location-link">
                <img src="{{block.content_block_image | url_for_generic_image}}" />
            </a>
        {% if forloop.index == content_blocks_length %}
            </div>
            </div>
        {% endif %}
    {% endfor %} 
    

    【讨论】:

      【解决方案2】:

      要从使用相同迭代器的最后一个循环停止的地方开始循环,请传递特殊单词 continue

      <!-- if array = [1,2,3,4,5,6] -->
      {% for item in array limit: 3 %}
        {{ item }}
      {% endfor %}
      {% for item in array limit: 3 offset: continue %}
        {{ item }}
      {% endfor %}
      

      这是一个教科书示例,说明如何做到这一点,但您必须在每次限制后重复代码,这很不舒服。您可以在以下位置找到更多信息:https://shopify.github.io/liquid/tags/iteration/

      所以我删除了我的版本并使用了Victor's,你只需要写一次。漂亮……

      【讨论】:

        猜你喜欢
        • 2019-04-01
        • 1970-01-01
        • 2014-09-14
        • 2015-07-17
        • 2015-07-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-08-28
        相关资源
        最近更新 更多