Parag Bhingre
Parag Bhingre

Reputation: 850

How to check whether array element is defined or not in twig file?

I am trying to access array but it is not getting accessed. in my config.yml following is my array :

abc : [xyz]

and in another file i am writing following code to access abc array.

 {% if abc[0] is defined) %}
then do something
  {% endif %}

but somehow its not working. please help me out i am newbie in this.

Upvotes: 3

Views: 2561

Answers (2)

user2831723
user2831723

Reputation: 892

Based on comments I would recommend using foreach loop instead and define your ifs based on index values. Something like this:

{% for abcs in abc %}
    {% if (loop.index == 0) %}
         then do something
    {% endif %}
{% endfor %}

BR's

Upvotes: 0

A.L
A.L

Reputation: 10483

It depends if the variable is always declared or not:

If the variable is always declared and the array can be empty

{% if abc is not empty %}
    {# then do something #}
{% endif %}

<variable> is not empty in Twig is equivalent to !empty($variable) in PHP. When an array is provided, is not empty will check there is a value and/or a value in the array.

empty test in Twig documentation.

If the variable is not always declared

Check that the abc variable is declared and not empty:

{% if (abc is declared) and (abc is not empty) %}
    {# then do something #}
{% endif %}

<variable> is declared in Twig is equivalent to isset($variable) in PHP.

defined test in Twig documentation.

Upvotes: 0

Related Questions