我有一个多维数组,其中某些对象存在,而另一些对象则没有。整个数据已在页面中使用。然后,我计划在树枝中检查一下。示例数据:
array:2[
0 => Data1 {
-id: 17
-porodType: "1d"
-name: "Dally promotion"
}
1 => Data1 {
-id: 34
-porodType: "S"
-name: "Special"
}
]
如何检查响应中是否存在使用porodtype =" 1d"记录?如何显示此诊断的不同消息:存在(OK(/no-exist(error(?
在Twig中检查时:
{% for d in Data1 %}
{% if d.porodType == '1d' %}
<button class="btn">OK</button>
{% else %}
<button class="btn"">Error</button>
{% endif %}
{% endfor %}
此代码结果是:<button class="btn">OK</button><button class="btn">Error</button>
,但我期望<button class="btn">OK</button>
或<button class="btn">ERROR</button>
如果您只想显示一个按钮,则需要跟踪使用标志的错误,因为您无法在Twig
中打破循环,
{% set error = false %}
{% for d in Data1 %}
{% if d.porodType != '1d' %}
{% set error = true %}
{% endif %}
{% endfor %}
{% if error %}
<button class="btn">Error</button>
{% else %}
<button class="btn">OK</button>
{% endif %}
使用twig for..if..else可能比当前接受的答案更简单:
{% for d in Data1 if d.porodType == "1.d" %}
<!-- show error button -->
{% else %}
<!-- show the okay button -->
{% endfor %}
循环为空时的其他子句(没有任何迭代(。
请参阅的文档标签:https://twig.sensiolabs.org/doc/2.x/tags/for.html