Skip to content

Jinja2 fails to iterate models in 0.8.0RC2/3 #311

@jbiason

Description

@jbiason

In 0.7.9, we could pass a QuerySet directly to Jinja2 and it would render without a problem; with 0.8.0, it seems checking the length resets the cursor, duplicating the displaying data.

For example, with the following model:

from mongoengine import Document
from mongoengine import StringField


class RandomData(Document):
    title = StringField()
    description = StringField()

And the following data:

from mongoengine import connect

from model import RandomData

connect('mongoengine_iterable')

examples = [('This is title', 'This is description'),
            ('Title', 'Description'),
            ('Not description', 'Not title')]

for (title, description) in examples:
    record = RandomData()
    record.title = title
    record.description = description
    record.save()

if you try to render the following template:

{% for record in content %}
    {{ record.title }} {{ record.description }} {% if loop.first -%}
        (This is first)
    {%- endif -%}{%- if loop.last -%}
        (this is last)
    {%- endif -%}
{% endfor %}

with this code:

from jinja2 import Environment
from jinja2 import PackageLoader
from jinja2 import FileSystemLoader

from model import RandomData

from mongoengine import connect

env = Environment(loader=FileSystemLoader(searchpath='./'))

template = env.get_template('display.tmpl')

connect('mongoengine_iterable')
data = RandomData.objects.all()

print template.render(content=data)

The first line will be repeated. If you remove the loop.last check, it works without a problem in 0.8.0.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions