Search code examples
phpsymfonytwig

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?


Solution

  • 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 %}