Twig 模板条件模式循环
Twig templating conditional pattern loop
我觉得这将是一个非常简单的解决方案,但我现在无法全神贯注。我正在使用 Twig 构建 Craft CMS 模板,并希望以特定模式布置一些元素(图库图像块)。类似于这个例子。 example photo
当我遍历每个元素时,我想适当地显示它们,无论大小。 sm, sm, lg, lg, sm, sm, 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
(function in 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
值,即 true
或 false
)。
该行相当于:
{% if reverse %}
{% set pattern = [sm, sm, lg] %}
{% else %}
{% set pattern = [lg, sm, sm] %}
{% endif %}
Ternary operator 对于有条件地将一些数据分配给变量非常方便。
我觉得这将是一个非常简单的解决方案,但我现在无法全神贯注。我正在使用 Twig 构建 Craft CMS 模板,并希望以特定模式布置一些元素(图库图像块)。类似于这个例子。 example photo
当我遍历每个元素时,我想适当地显示它们,无论大小。 sm, sm, lg, lg, sm, sm, 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
(function in 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
值,即 true
或 false
)。
该行相当于:
{% if reverse %}
{% set pattern = [sm, sm, lg] %}
{% else %}
{% set pattern = [lg, sm, sm] %}
{% endif %}
Ternary operator 对于有条件地将一些数据分配给变量非常方便。