在 Twig 中,检查数组的特定键是否存在

在 PHP 中,我们可以使用函数 array_key_exists()检查数组中是否存在键。

在 Twig 模板语言中,我们可以通过使用 if语句检查变量或对象的属性是否存在,如下所示:

{% if app.user %}
do something here
{% else %}
do something else
{% endif %}

但是我们如何使用 Twig 检查 数组的键是否存在?我试了 {% if array.key %},但它给了我一个错误:

Key "key" for array with keys "0, 1, 2, 3...648" does not exist

由于将数据传递到模板的主要方法之一是使用数组,因此似乎应该有一些方法可以实现这一点。有什么想法吗?

132553 次浏览

Twig example:

{% if array.key is defined %}
// do something
{% else %}
// do something else
{% endif %}

You can use the keys twig function

{% if myVar in someOtherArray|keys %}

Quick Answer (TL;DR)

  • DeveloperTLindel wants to test for existence of array key in Twig.
  • DeveloperTLindel wants to trap any errors associated with undefined key.
  • This can be handled using the default filter.

Detailed Answer

Context

  • Twig 2.x (latest version as of Wed 2017-03-08)
  • General-purpose use of the default filter.

Problem

  • Scenario:
  • DeveloperTLindel wants to test for existence of array key in Twig.
  • DeveloperTLindel wants to avoid any errors or exceptions caused by potentially undefined key.

Solution

  • DeveloperTLindel can use the default filter.
  • The default filter catches any exceptions owing to undefined variable, and allows short-circuit substition of an alternate value.
  • The default filter is chainable.

Example01



{#- ****************************************
testing for a single key in associative array
-#}
{%- set mystring = myarray['key-no-existo'] |default('__BLANK__')  -%}


{#- ****************************************
testing for a multiple keys in associative array
-#}
{%- set mystring = myarray['alpha']
|default(myarray['bravo'])
|default(myarray['charlie'])
|default('__BLANK__')
-%}


See also