I have a list like
users = ['tom', 'dick', 'harry']
In a Jinja
template I'd like to print a list of all users except tom
joined. I cannot modify the variable before it's passed to the template.
I tried a list comprehension, and using Jinja's reject
filter but I haven't been able to get these to work, e.g.
{{ [name for name in users if name != 'tom'] | join(', ') }}
gives a syntax error.
How can I join list items conditionally?
Jinja in-line conditionals are started with a curly brace and a % symbol, like {% if condition %} and closed with {% endif %} . You can optionally include both {% elif %} and {% else %} tags.
Use the jinja2 {% include %} directive. This will include the content from the correct content-file. Show activity on this post. You can use the include statement.
Jinja2 works with Python 2.6. x, 2.7. x and >= 3.3. If you are using Python 3.2 you can use an older release of Jinja2 (2.6) as support for Python 3.2 was dropped in Jinja2 version 2.7.
Use reject
filter with sameas
test:
>>> import jinja2
>>> template = jinja2.Template("{{ users|reject('sameas', 'tom')|join(',') }}")
>>> template.render(users=['tom', 'dick', 'harry'])
u'dick,harry'
UPDATE
If you're using Jinja 2.8+, use equalto
instead of sameas
as @Dougal commented; sameas
tests with Python is
, while equalto
tests with ==
.
This should work, as list comprehension is not directly supported. Ofcourse, appropiate filters will be better.
{% for name in users if name != 'tom'%}
{{name}}
{% if not loop.last %}
{{','}}
{% endif %}
{% endfor %}
Another solution with "equalto" test instead of "sameas"
Use reject filter with equalto test:
>>> import jinja2
>>> template = jinja2.Template("{{ items|reject('equalto', 'aa')|join(',') }}")
>>> template.render(users=['aa', 'bb', 'cc'])
u'bb,cc'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With