在 Twig 中,检查数组的特定键是否存在 [英] In Twig, check if a specific key of an array exists
问题描述
在 PHP 中,我们可以使用函数 array_key_exists()
来检查数组中是否存在键.
In PHP we can check if a key exists in an array by using the function array_key_exists()
.
在 Twig 模板语言中,我们可以通过使用 if
语句来检查变量或对象的属性是否存在,如下所示:
In the Twig templating language we can check if an variable or an object's property exists simply by using an if
statement, like this:
{% if app.user %}
do something here
{% else %}
do something else
{% endif %}
但是我们如何使用 Twig 检查数组的键是否存在?我试过 {% if array.key %}
,但它给了我一个错误:
But how do we check if a key of an array exists using Twig? I tried {% if array.key %}
, but it gives me an error:
Key "key" for array with keys "0, 1, 2, 3...648" does not exist
由于将数据传递到模板的主要方法之一是使用数组,因此似乎应该有某种方法可以做到这一点.有什么想法吗?
As one of the primary ways of passing data into a template is using arrays, it seems like there should be some way of doing this. Any thoughts?
推荐答案
Twig 示例:
{% if array.key is defined %}
// do something
{% else %}
// do something else
{% endif %}
这篇关于在 Twig 中,检查数组的特定键是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!