使用 Timber 和 Twig 对循环中的项目进行分组的解决方案

A solution for grouping items in loop with Timber and Twig

我经常需要对画廊等动态元素进行一些棘手的布局。 这是一个例子:

<ul>
<li class="slide">
    <img src="img_01.jpg">
    <img src="img_02.jpg">
</li>
<li class="slide">
    <img src="img_03.jpg">
    <img src="img_04.jpg">
</li>
<li class="slide">
    <img src="img_05.jpg">
    <img src="img_06.jpg">
</li>
</ul>

我已经通过以下代码片段成功完成了。但如果可能的话,我想要一些关于如何使它更灵活或更简单的建议,比如按任意数字分组。也许使用 cycle() 或任何其他方法。我使用 slice() 或 array[1:2] 表示法得到了奇怪的结果。

<ul>
{% for image in gallery %}
{% set current = loop.index %}
{% set next = current + 1 %}
    {% if current is odd %}
        <li class="slide">
            {% for image in gallery %}
                {% if loop.index in [current,next] %}
                {% set th = TimberImage(image) %}
                    <img src="{{th.src}}">
                {% endif %}
            {% endfor %}
        </li>
    {% endif %}
{% endfor %}
</ul>

欢迎提出任何建议。 对于使用 Timber::compile 或具有完整路由的自定义主题进行快速进出修复,Timber 变得非常方便。问题的目的是创建一些可以重复使用的片段。

感谢创作者。 https://github.com/timber/timber

您可以使用以下代码(Here 一个可行的解决方案)处理 rest of the division

{# number of element for every section #}
{% set section = 2%}

<ul>
{% for image in gallery %}
   {% if loop.index % section == 1  %}
     <li class="slide">
   {% endif %}
   {% set th = TimberImage(image) %}
       <img src="{{th.src}}">
   {% if loop.index % section == 0 or loop.last %}
     </li>
  {% endif %}
{% endfor %}
</ul>

您可以轻松地重复使用此代码制作 Twig macro,使用图库和部分元素的数量作为参数(使用变量 section

突出显示

这是采用@Matteo 对宏的建议的最终结果: https://gist.github.com/lithiumlab/5ee0454b0a77b1cc26fc0ce8ba52fd80

views/single.树枝:

{% import 'utils.twig' as utils %}
{{utils.group_collection(gallery,3)}}

views/utils.树枝:

{% macro group_collection(collection, groupby) %}
{% set section = groupby|default(2) %}

    <ul>
    {% for element in collection %}
       {% if loop.index % section == 1  %}
         <li class="group">
       {% endif %}
       {% set th = TimberImage(element) %}
           <img src="{{th.src}}">
       {% if loop.index % section == 0 or loop.last %}
         </li>
      {% endif %}
    {% endfor %}
    </ul>

{% endmacro %}