6

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?

4 Answers 4

13

You could also try the default filter:

{{ item.price|default("nothing") }}
Sign up to request clarification or add additional context in comments.

Comments

12

Go to config.yml and set the following there:

twig:
    strict_variables: false

Comments

5
{% 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 :)

1 Comment

A bit nicer replacement is {% if item.price is defined and item.price not empty %}, though my vote goes to @Problematic answer.
2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.