How do you check if an object exists in the Twig template engine in Symfony2?

I have a multidimensional array where some objects exist and others do not. I keep getting

The "code" method for the "stdClass" object does not exist in ... ?

The code I use in my template is:

{% for item in items %} <p>{% if item.product.code %}{{ item.product.code }}{% endif %}</p> {% endfor %} 

Some products do not have this code, and, unfortunately, this data structure is provided through the feed, so I canโ€™t change it.

When I looked at the Twig documentation, I realized that if the object or method was not there, would it just return null?

+81
symfony twig
Aug 11 '11 at 23:17
source share
2 answers

Quickly looked through, hope this works for you: p

defined

checks are defined if the variable is defined in the current context. This is very useful if you use the strict_variables option:

 {# defined works with variable names #} {% if foo is defined %} ... {% endif %} {# and attributes on variables names #} {% if foo.bar is defined %} ... {% endif %} 
+144
Aug 12 '11 at 5:21
source share

If you check the key / variable inside a multidimensional array, then (if object.object.key defined) does not work for me.

But (if object.object['key'] defined) or (if object.object.get('key') defined) works well.

0
Jul 20 '17 at 15:01
source share



All Articles