pohofo
pohofo

Reputation: 99

Set default value if null in twig

I am looping my results in twig view..

{% for item in items %}
    <li> {{ item.userId.firstName }} {{ item.userId.lastName }} </li>
 {% endfor %}

I want to set default value 'User unknown' if the user id in database is NULL .

Like: {% if item.userId is null %} --> than set default value

Note: I am aware of using if else here but as I have this fistName - lastName in numerous palace, I wanted to avoid using if else in every part. I wanted to set that default value everywhere in case userId is null without repeating the code in every place.

How can I accomplish that?

Upvotes: 3

Views: 10508

Answers (3)

Michel FW
Michel FW

Reputation: 151

Maybe a bit late, but Twig seems to have a filter for default values:

https://twig.symfony.com/doc/2.x/filters/default.html

Upvotes: 2

Alister Bulman
Alister Bulman

Reputation: 35169

It may be easier to set defaults in the code that is rendering the output, where items is being sent to Twig. array_merge is often used for this - $item = array_merge($defaultItem, $item);. Here, $item overrides the value set in defaults.

Within the templates, you can also use the null-coalescing operator ?? on individual fields: {{ item.userId.firstName ?? 'unknown firstName' }}

Upvotes: 2

ImAtWar
ImAtWar

Reputation: 1143

EDIT

You can set a variable by using:

{% set name = item.userId is null ? 'User unknown' : item.userId.firstName ~ ' ' ~ item.userId.lastName %}

If by setting you mean outputting 'User unknown', a simple if else statement would do the trick

{% for item in items %}
    {% if item.userId is null %}
        <li>User unknown</li>
    {% else %}
        <li> {{ item.userId.firstName }} {{ item.userId.lastName }} </li>
    {% endif %}
{% endfor %}

Upvotes: 4

Related Questions