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?
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.
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.
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.
You could also try the default
filter:
{{ item.price|default("nothing") }}
Go to config.yml and set the following there:
twig:
strict_variables: false
{% 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 :)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With