树枝模板条件模式循环



我有一种感觉,这将是一个非常简单的解决方案,但我现在无法理解它。我正在使用 Twig 构建一个 Craft CMS 模板,并希望以特定模式布局一些元素(图库图像块)。与此示例类似。示例照片

当我遍历每个元素时,我想适当地显示它们,无论大小。 SM, SM, LG, LG, SM, SM, LG, LG... 等等。

我知道我显然可以像这样预演一个循环

{% if loop.index is even %}
...
{% endif %}

或者像这个结果 [sm, sm, lg, sm, sm lg]

{% if loop.index is divisible by(3) %}
...
{% endif %}

但我的模式有点复杂。

谢谢,你的帮助。

您想要的图案是正常sm sm lg打印,然后反转,然后正常打印...

sm sm lg lg sm sm sm sm lg ...

您可以创建一个输出此模式的macro(Twig 中的函数):

{% macro printPattern(reverse = false) %} {# the function AKA macro signature #}
{% set sm = 'a small image' %} {# Make this an <img> tag. #}
{% set lg = 'a large image' %}
{% set pattern = (reverse) ? [lg, sm, sm] : [sm, sm, lg] %}
{% for n in pattern %}{{ n }} {% endfor %}
{% endmacro %}
{# If you wanted to use the macro in the same file you must include: #}
{% import from _self as helper %}
{# Then call the macro: #}
{{ helper.printPattern(false) }}
{{ helper.printPattern(true) }}
{{ helper.printPattern() }} {# This does the same as helper.printPattern(false) #}
{# because we set a default value for the passed-in variable in the macro's signature. #}


特别提示:

我在此行中使用了ternary运算符?

{% set pattern = (reverse) ? [lg, sm, sm] : [sm, sm, lg] %}

(回想一下,reverse是一个boolean值,即truefalse)。

该行等效于:

{% if reverse %}
{% set pattern = [sm, sm, lg] %}
{% else %}
{% set pattern = [lg, sm, sm] %}
{% endif %}

三元运算符对于有条件地将一些数据分配给变量非常方便。

最新更新