Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Twig Empty Variable -> Exception?

Tags:

twig

symfony

I am running through a loop in Twig:

{% for item in items %}
<div class="description">
   Title: {{ item.name }}<br />
   Price: {{ item.price }}
</div>
{% else %}
<p>...</p>
{% endfor %}

If item.price is empty, it throws me an exception. Can't I just simply force Twig to give out "nothing" when a certain value is empty?

Or do I always need to {% if item.x %}{{ item.x }}{% endif %} for all values?

like image 786
Mike Avatar asked Oct 24 '11 17:10

Mike


People also ask

How check variable is empty in twig?

empty checks if a variable is an empty string, an empty array, an empty hash, exactly false , or exactly null . For objects that implement the Countable interface, empty will check the return value of the count() method.

Is defined twig template?

Twig is a template engine for the PHP programming language. Its syntax originates from Jinja and Django templates. It's an open source product licensed under a BSD License and maintained by Fabien Potencier. The initial version was created by Armin Ronacher.

What is Twig Environment?

Twig uses a central object called the environment (of class \Twig\Environment ). Instances of this class are used to store the configuration and extensions, and are used to load templates. Most applications create one \Twig\Environment object on application initialization and use that to load templates.


4 Answers

You could also try the default filter:

{{ item.price|default("nothing") }}
like image 98
Derek Stobbe Avatar answered Oct 03 '22 15:10

Derek Stobbe


Go to config.yml and set the following there:

twig:
    strict_variables: false
like image 29
Vladislav Rastrusny Avatar answered Oct 03 '22 17:10

Vladislav Rastrusny


{% if item.price is defined and item.price not in [''] %}
    {{ item.price }}
{% endif %}

Should do the trick, or that is at least how I have handled it in the past. I am not a Twig expert though :)

like image 31
Kurt Funai Avatar answered Oct 03 '22 15:10

Kurt Funai


This is my shortest version for this situation:

{{ item.price|default }}

default-filter's default is FALSE, so it will output nothing and not raise an exception.

like image 43
Möhre Avatar answered Oct 03 '22 16:10

Möhre