103

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?

dreftymac
  • 31,404
  • 26
  • 119
  • 182
user852610
  • 2,205
  • 7
  • 36
  • 46
  • Twig is just a template engine. You know it right? – itachi Nov 28 '12 at 14:28
  • 4
    You can use "attribute" function: http://twig.sensiolabs.org/doc/functions/attribute.html {% if attribute(array, key) is defined %} // do something {% endif %} – Dennais Mar 13 '15 at 14:47
  • @Vega You should add that as an answer, as it seems to be the only way to check for a key that isn't a single word, like `data-value`. – insertusernamehere Oct 26 '15 at 10:09

4 Answers4

236

Twig example:

{% if array.key is defined %}
  // do something
{% else %}
  // do something else
{% endif %}
phpisuber01
  • 7,585
  • 3
  • 22
  • 26
  • 2
    Why can't we just use `{% if array.key %}`? What's wrong with it? In JS it's perfectly valid statement but not in Twig! – Dmitry Feb 11 '16 at 18:49
  • 3
    `{% if array.key %}` is valid, but it's the syntax to check if the array key is empty. [twig.sensiolabs.org/doc/tags/if.html#if](http://twig.sensiolabs.org/doc/tags/if.html#if) – bats-everywhere Aug 28 '16 at 05:02
  • 30
    If key is a variable, you need to use `{% if array[ key ] %}` or `{% if array[ key ] is defined %}`. `array.key` tries to access index 'key' in the array. – MarthyM Dec 01 '16 at 08:36
38

You can use the keys twig function

{% if myVar in someOtherArray|keys %}

Samir Patel
  • 805
  • 7
  • 9
4

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

Community
  • 1
  • 1
dreftymac
  • 31,404
  • 26
  • 119
  • 182
1

SYMFONY 6

solution is quite simple TWIG is looking for variable passed when $this->render is called in Controller.

  1. create your pack data like

                 $options = [
                     'companyLogo' => $company->getCompanyLogoLink(),
                     'companyName' => $company->getCompanyShortname(),
                     'menuItem'    => $companyMenuCategories,
    
             ];
    
  2. pass it to TWIG

    return $this->render('folder/template.html.twig', [ 'o' => $options, ]);

  3. in twig just look for 'passed' key ( o ) and array data with it

       {% if o.companyName is defined %}
         {{ o.companyName }}
       {% endif %}
    
zoore
  • 293
  • 5
  • 13