LLaP
LLaP

Reputation: 2727

How to use a variable inside of if statement in jinja2?

I receive a list(categories) from Python application which I iterate over. I would like to define a variable based on input from this list, concatanete it with a string and use it for a further loop. After concatenation, the string literal of atom_type refers to another list from an application.

{% for c in categories %}

{% set atom_type = 'atoms_' + c %}

{% for atom in atom_type %}

{% endfor %}
{% endfor %}

The problem is that, in the second for loop atom_type is treated as a string, and not as an object. How do you use atom_type variable to refer to an object(python list)?

Upvotes: 1

Views: 1705

Answers (1)

Esparta Palma
Esparta Palma

Reputation: 745

You can construct the categories as a list of dicts, pass them to the template and use the groupby() filter:

<ul>
{% for atoms in categories|groupby('atom_type') %}
    <li>{{ group.grouper }}<ul>
    {% for atom in group.list %}
        <li>{{ atom.name }} {{ atom.weight }}</li>
    {% endfor %}</ul></li>
{% endfor %}
</ul>

Upvotes: 1

Related Questions