use*_*610 68 php arrays conditional short-circuiting twig
在PHP中,我们可以使用该函数检查数组中是否存在键array_key_exists()
.
在Twig模板语言中,我们可以通过使用if
语句来检查变量或对象的属性是否存在,如下所示:
{% if app.user %}
do something here
{% else %}
do something else
{% endif %}
Run Code Online (Sandbox Code Playgroud)
但是我们如何使用Twig 检查数组的键是否存在?我试过了{% if array.key %}
,但它给了我一个错误:
Key "key" for array with keys "0, 1, 2, 3...648" does not exist
Run Code Online (Sandbox Code Playgroud)
由于将数据传递到模板的主要方法之一是使用数组,似乎应该有一些方法来做到这一点.有什么想法吗?
php*_*r01 162
Twig例子:
{% if array.key is defined %}
// do something
{% else %}
// do something else
{% endif %}
Run Code Online (Sandbox Code Playgroud)
小智 19
您可以使用keys
树枝功能
{% if myVar in someOtherArray|keys %}