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

时间:2016-10-16 00:26:02

标签: twig timber

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

<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 ::编译或自定义主题和完整路由。问题的目的是创建一些可以重用的代码段。

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

2 个答案:

答案 0 :(得分:3)

您可以使用以下代码(Here一个有效的解决方案)使用<NSLayoutYAxisAnchor:0x174076c00 "UILayoutGuide:0x174191e00'UIViewLayoutMarginsGuide'.bottom">

rest of the division

您可以轻松地重复使用此代码,使用Twig macro作为参数使用库和部分的元素数(使用变量{# 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> 突出显示

答案 1 :(得分:1)

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

视图/ single.twig:

start

视图/ utils.twig:

{% import 'utils.twig' as utils %}
{{utils.group_collection(gallery,3)}}
相关问题