Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditionally join a list of strings in Jinja

Tags:

python

jinja2

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?

like image 234
skyler Avatar asked Jun 04 '14 15:06

skyler


People also ask

How do you write if condition in Jinja?

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.

How do I include in Jinja?

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.

Does Jinja2 work with Python 3?

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.


3 Answers

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 ==.

like image 177
falsetru Avatar answered Oct 02 '22 13:10

falsetru


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 %}
like image 13
bendtherules Avatar answered Oct 02 '22 15:10

bendtherules


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'
like image 1
N. Chamaa Avatar answered Oct 02 '22 14:10

N. Chamaa