Reputation: 2735
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?
Upvotes: 6
Views: 4053
Reputation: 939
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.
Upvotes: 2
Reputation: 30013
Go to config.yml and set the following there:
twig:
strict_variables: false
Upvotes: 12
Reputation: 17678
You could also try the default
filter:
{{ item.price|default("nothing") }}
Upvotes: 13
Reputation: 654
{% 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 :)
Upvotes: 5