Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

twig

symfony

I have a multidimensional array where some objects exist and others don't. I keep getting a

Method "code" for object "stdClass" does not exist in...?

The code I am using 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 via a feed, so I cannot change it.

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

like image 458
Adam Stacey Avatar asked Aug 11 '11 23:08

Adam Stacey


People also ask

Is Twig a template engine?

Twig is a template engine for the PHP programming language.

Which of the given features are provided by Twig?

Twig is a modern template engine for PHP Fast: Twig compiles templates down to plain optimized PHP code. The overhead compared to regular PHP code was reduced to the very minimum. Secure: Twig has a sandbox mode to evaluate untrusted template code.


1 Answers

Quickly did a lookup, hope this is works for you :p

defined

defined checks if a 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 %} 
like image 185
Tjorriemorrie Avatar answered Sep 29 '22 06:09

Tjorriemorrie