K
K
kapai692015-02-19 22:17:00
symfony
kapai69, 2015-02-19 22:17:00

Twig how to check the existence of an array key?

I check as follows

{% if myKey in items|keys %}
        {{ items[myKey].name }}
{% endif %}

The problem is that if there is no such key, then it refers to it in the if body, and gives an error that the access to a non-existent key. How to avoid it?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
Y
Yuri, 2015-02-22
@error500

Try{% if items[myKey] is defined %}

A
Alexey Krichko, 2015-02-27
@sand_alkr

{% if items[myKey]|default(false) %}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question