shuffle
3.11
shuffle
过滤器在 Twig 3.11 中添加。
shuffle
过滤器会打乱序列、映射或字符串
1 2 3
{% for user in users|shuffle %}
...
{% endfor %}
注意
打乱后的数组不保留键。因此,如果输入没有顺序键而是索引键(例如使用用户 ID),那么在打乱后情况就不是这样了。
示例 1
1 2 3 4 5 6 7 8 9 10 11
{% set items = [
'a',
'b',
'c',
] %}
<ul>
{% for item in items|shuffle %}
<li>{{ item }}</li>
{% endfor %}
</ul>
上面的示例将呈现为
1 2 3 4 5
<ul>
<li>a</li>
<li>c</li>
<li>b</li>
</ul>
结果也可能是:"a, b, c" 或 "b, a, c" 或 "b, c, a" 或 "c, a, b" 或 "c, b, a"。
示例 2
1 2 3 4 5 6 7 8 9 10 11
{% set items = {
'a': 'd',
'b': 'e',
'c': 'f',
} %}
<ul>
{% for index, item in items|shuffle %}
<li>{{ index }} - {{ item }}</li>
{% endfor %}
</ul>
上面的示例将呈现为
1 2 3 4 5
<ul>
<li>0 - d</li>
<li>1 - f</li>
<li>2 - e</li>
</ul>
结果也可能是:"d, e, f" 或 "e, d, f" 或 "e, f, d" 或 "f, d, e" 或 "f, e, d"。
1 2 3
{% set string = 'ghi' %}
<p>{{ string|shuffle }}</p>
上面的示例将呈现为
1
<p>gih</p>
结果也可能是:"ghi" 或 "hgi" 或 "hig" 或 "igh" 或 "ihg"。