Search code examples
sourcery

Detect if a forloop has zero loops


I'm trying to handle a case where a forloop with a where clause results in zero loops.

I've tried using set and map in various ways unsuccessfully, possibly one of those is the solution but I just couldn't get it right.

{% for variable in type.allVariables where variable.type.implements["SomeProtocol"]["name"] == "SomeProtocol" %}
// Add code for each variable
{% endfor %}
// Add backup code if forloop didn't do a single loop

Solution

  • Found the answer in the stencil documentation of all places - who knew!

    The for tag can take an optional {% empty %} block that will be displayed if the given list is empty or could not be found.

    {% for user in users %}
        <li>{{ user }}</li>
    {% empty %}
        <li>There are no users.</li>
    {% endfor %}