1

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

<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 对于使用 Timber::compile 或具有完整路由的自定义主题进行快速进出修复非常方便。这个问题的目的是创建一些可以重复使用的代码片段。

向创作者致敬。 https://github.com/timber/timber

4

2 回答 2

3

您可以使用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 宏,使用画廊和节的元素数量作为参数(用变量突出显示section

于 2016-10-16T06:34:23.277 回答
1

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

意见/single.twig:

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

视图/utils.twig:

{% 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 %}
于 2016-10-16T22:13:16.290 回答