In Twig, check if a specific key of an array exists

纵然是瞬间 提交于 2019-11-29 04:20:14

问题


In PHP we can check if a key exists in an array by using the function array_key_exists().

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 %}

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?


回答1:


Twig example:

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



回答2:


You can use the keys twig function

{% if myVar in someOtherArray|keys %}




回答3:


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

  • SO: Similar question related to non-existent or null variables
  • SO: General purpose use of default filter


来源:https://stackoverflow.com/questions/13607241/in-twig-check-if-a-specific-key-of-an-array-exists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!