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

前端 未结 3 679
离开以前
离开以前 2020-12-15 02:06

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

相关标签:
3条回答
  • 2020-12-15 02:48

    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
    0 讨论(0)
  • 2020-12-15 02:54

    You can use the keys twig function

    {% if myVar in someOtherArray|keys %}

    0 讨论(0)
  • 2020-12-15 03:05

    Twig example:

    {% if array.key is defined %}
      // do something
    {% else %}
      // do something else
    {% endif %}
    
    0 讨论(0)
提交回复
热议问题