2016-12-30 159 views
0

我有一种感觉,这将是一个非常简单的解决方案,但我现在无法围绕它解决它。我正在用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 %} 

,但我的结果模式稍微复杂一些。

谢谢,寻求帮助。

+2

我不确定你想在这里捕捉什么样的图案。 – JETM

+0

是的,请明确说明您可能需要什么! –

+0

我基本上想要在前两次触发“真”,然后“假”两次,然后“真”四次,如此类推(如上图)。 –

回答

0

你想要的图案是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. #} 

Example


特别说明:

我使用的操作者ternary?在这条线:

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

(回想reverseboolean值,即truefalse)。

该行等同于:

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

Ternary operator是对于一些有条件的数据赋值给一个变量非常方便。

+0

好的,我一直在玩你的代码,我想我在正确的页面上,但是当涉及到在模式中实现变量时,我有点失落。这是我的。 https://twigfiddle.com/xld36e 在什么时候我会查看一组三个变量来实现模式? –

+0

@TimCook,该链接指向我的示例。你有保存吗? – Rhono

+0

我以为我更新了,尝试twigfiddle。com/xld36e/2 –