Twig 测试变量是否可iterable:是否需要先检查它是否已定义?
我习惯于在树枝上这样做:Twig 测试变量是否可iterable:是否需要先检查它是否已定义?,twig,Twig,我习惯于在树枝上这样做: {% if entities is defined and entities is not null and entities|length > 0 %} .... {% endif %} 现在我遇到了Iterable测试-> 这样做是否足够: {% if entities is iterable %} 还是我还需要这样做 {% if entities is defined and entities is iterable %} 总而言之:iterable检
{% if entities is defined and entities is not null and entities|length > 0 %}
....
{% endif %}
现在我遇到了Iterable测试->
这样做是否足够:
{% if entities is iterable %}
还是我还需要这样做
{% if entities is defined and entities is iterable %}
总而言之:iterable检查是执行“已定义”还是抛出错误
And:空数组是否可编辑
提前感谢。如果您可能无法将变量传递给模板,您需要在测试该变量是否可编辑之前检查该变量是否已定义,否则您将得到一个异常,即变量“实体”不存在。因此,正确的方法是:
{% if entities is defined and entities is iterable %}
但是,如果始终传递一个变量,但不确定该变量是否可iterable,则只需使用iterable检查,而无需测试定义的:
{% if entities is iterable %}
否则,如果总是在变量中传递iterable集合,但不确定它是否为空,则不需要检查iterable,只需使用for
循环(以及else
语句,如果需要):
如果可能无法将变量传递给模板,则需要在测试该变量是否可编辑之前检查该变量是否已定义,否则会出现异常,即变量“实体”不存在。因此,正确的方法是:
{% if entities is defined and entities is iterable %}
但是,如果始终传递一个变量,但不确定该变量是否可iterable,则只需使用iterable检查,而无需测试定义的:
{% if entities is iterable %}
否则,如果总是在变量中传递iterable集合,但不确定它是否为空,则不需要检查iterable,只需使用for
循环(以及else
语句,如果需要):
如果要避免使用多个条件,可以使用为未定义的变量提供默认值
{% if entities|default(null) is iterable %}
如果要直接迭代可能未定义的实体
变量:
{% for entity in entities|default([]) %}
...
{% else %}
No entities to display
{% endfor %}
如果要避免使用多个条件,可以使用为未定义的变量提供默认值
{% if entities|default(null) is iterable %}
如果要直接迭代可能未定义的实体
变量:
{% for entity in entities|default([]) %}
...
{% else %}
No entities to display
{% endfor %}