symfony - Twig3:如何使用循环 bariable 迁移“for item in items if item.foo == 'bar'”
问题描述
我使用以下 Twig 2 代码:
{% for item in items if item.foo == 'bar' %}
<span class="{% if loop.index % 2 %}special-class{% endif %}">
{{ item.value }}
</span>
{% else %}
Nothing found
{% endfor %}
在树枝文档中:https ://twig.symfony.com/doc/2.x/deprecated.html
在 Twig 2.10 中不推荐在 for 标记上添加 if 条件。在“for”正文中使用
filter
过滤器或“if”条件(如果您的条件取决于循环内更新的变量)
我想知道如何将我的 Twig 2 代码迁移到 Twig 3。如您所见,我使用循环变量并else
在 for 循环中。我知道我可以使用一个新参数并自己增加它......但这真的是意图吗?如何使用 重写此代码filter
?
解决方案
你有两个选择来解决这个问题
- 将
if
-tag 放在循环内
{% set i = 0 %}
{% for item in items %}
{% if item.foo == 'foo' %}
<span class="{% if i % 2 %}special-class{% endif %}">
{{ item.value }}
</span>
{% set i = i + 1 %}
{% endif %}
{% else %}
Nothing found
{% endfor %}
使用此解决方案,您不能“依赖”内部loop
变量,因为无论是否满足条件,计数器都会持续上升
- 使用
filter
- 过滤器
{% for item in items | filter(item => item.foo == 'foo') %}
<span class="{% if loop.index % 2 %}special-class{% endif %}">
{{ item.value }}
</span>
{% else %}
Nothing found
{% endfor %}
推荐阅读
- mysql - 有效地选择按列分组的最新行
- c++ - 添加新对话框后,MFC 应用程序启动失败并显示“DLL 初始化失败”
- progressive-web-apps - 如何在工作箱运行时缓存中排除 url?
- android - AppCenter Xamarin.Android 在设备上成功构建和安装,但无法运行
- scala - 如何在 IntelliJ 中为 Maven scala+spark 项目创建 .jar 文件
- android - 如何解决索引越界?
- css - Flexbox 渲染被最新的 Chrome 破坏
- python - Jupyter Notebook 5.7.6(上次更新)显示空白页
- c++ - 如何实现一个奇怪的for循环
- javascript - 在 Javascript 中使用“this”作为函数应用