specifying either-or value

12 views
Skip to first unread message

Jacob G

unread,
Nov 2, 2015, 12:44:27 PM11/2/15
to Nunjucks
I'd like to do something like this:

{{ value1 || value2 }}

Obviously, that's not valid syntax. I'm wondering if there is a more concise syntax than doing:

{% if value1 %}{{ value1 %}{%else %}{{ value2 }}{% endif %}

If there is not, then I might make a filter as follows:

{{ value1 | or(value2) }}

Carl Meyer

unread,
Nov 2, 2015, 12:59:05 PM11/2/15
to nunj...@googlegroups.com
Hi Jacob,
This is spelled {{ value1 or value2 }}.

Nunjucks derives from Jinja2, which derives its boolean operators from
Python, which uses the English words `and`, `or`, and `not`.

You can also spell it using the built-in `default` filter, like

{{ value1|default(value2, true) }}

The second argument `true` causes `value2` to be used if `value1` is
anything falsy; normally the `default` filter only uses the default if
`value1` is undefined. But I think that spelling is strictly inferior to
using `or`.

Carl

signature.asc

Jacob G

unread,
Nov 2, 2015, 1:04:03 PM11/2/15
to Nunjucks
That's perfect! Thanks so much Carl. I appreciate you getting me on track.
Reply all
Reply to author
Forward
0 new messages