Twig

灵活、快速且安全的
PHP 模板引擎

a Symfony Product
文档 函数 cycle
您正在阅读 Twig 3.x 的文档。切换到 Twig 1.x, 2.x 的文档。

问题与反馈

许可

Twig 文档 基于新 BSD 许可 授权。

cycle

cycle 函数循环访问一个序列

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
{% set start_year = date() | date('Y') %}
{% set end_year = start_year + 5 %}

{% for year in start_year..end_year %}
    {{ cycle(['odd', 'even'], loop.index0) }}
{% endfor %}

{# outputs

    odd
    even
    odd
    even
    odd
    even
    
#}

cycle 函数接受两个参数:要循环访问的 sequence 和序列中的 position

sequence 必须是非空的,并且可以包含任意数量的值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
{% set fruits = ['apple', 'orange', 'citrus'] %}

{% for i in 0..10 %}
    {{ cycle(fruits, i) }}
{% endfor %}

{# outputs

    apple
    orange
    citrus
    apple
    orange
    citrus
    apple
    orange
    citrus
    apple
    orange

#}

参数

  • values:要循环访问的序列
  • position:序列中的位置