pythonflaskjinja2quarttortoise-orm

Jinja2 - Object behaving differently inside for loop


I have an object (a QuerySet result from an ORM called tortoise-orm, but I think it doesn't matter) that behaves differently if I iterate it with a Jinja2's for loop.

Consider the object tasks as an iterable object.

For example, this works fine, it outputs the name of each task responsible, it is the fix I'm currently using:

{% for i in range(tasks|length) %}
    {% set task = tasks[i] %}
    <li>{{task.responsible.name}}</li>
{% endfor %}

But this just creates a bunch of blank <li> with no errors :

{% for task in tasks %}
    <li>{{task.responsible.name}}</li>
{% endfor %}

And this works just fine too :

<h1>{{tasks[0].responsible.name}}</h1>

So, after banging my head for a long time, I think it might be related to how Jinja accesses iterables and how this particular object implemented its own iterable, but since I'm not willing to modify either library, I'm just looking for a solution and maybe a simple explanation on how to avoid future issues like this

What could be happening here?


Solution

  • If the object you're dealing with is a generator (as opposed to a list), once you've consumed it via tasks|length, that's it. You can't start over. If you really need its size, convert the generator to a list in the handler (e.g., by passing list(tasks) instead of tasks.