yesno Filter

Logic Most Useful

Argument: mapping (Optional) – return values for True, False, and (optionally) None.

Documentation

The yesno filter maps values that evaluate to True, False, and None to "yes", "no", and "maybe" or to alternative strings passed in as a comma-delimited string.

Variable

inventory = {
    'gloves': 0,
    'hats': 51,
    'scarves': 2,
    'socks': 13
}

Template

<ol>
{% for item, remaining in inventory.items %}
  <li class="{{ remaining|yesno:'instock,outofstock' }}">
    {{ item }}: {{ remaining }} remaining
    {{ remaining|yesno:',(time to place an order)' }}
  </li>
{% endfor %}
</ol>

Notice how the yesno filter is used once to determine the class value and again to determine whether or not to output “(time to place an order)”.

Result

<ol>
<li class="outofstock">gloves: 0 remaining (time to place an order)</li>
<li class="instock">hats: 51 remaining</li>
<li class="instock">scarves: 2 remaining</li>
<li class="instock">socks: 13 remaining</li>
</ol>

Commentary

This is particularly useful for selecting class names for HTML elements.


Did we get something wrong? Is there a use case for the yesno filter that we should add? Please let us know.

Send Feedback

Official Documentation
This page last updated on Oct. 30, 2022, 1:21 p.m. EST