Iterate over the same list twice in Jinja2?

2019-04-27 21:23发布

I'm trying to print a list of tags in two separate places, but the second time I for/in the list, it doesn't loop.

<ul>
# for tag in tags
    <li><a href="/my-tags/{{tag.name}}">{{tag.name}}</a></li>
# endfor
</ul>

<ul>
# for tag in tags
    <li><a href="/my-tags/{{tag.name}}">{{tag.name}}</a></li>
# endfor
</ul>

The second UL ends up empty if I put that in my template.

Any ideas?

Edit:

This is how I'm populating the tags variable.

contact_data.append({'name': 'Placeholder', 'emails': contact.emails, 'tags': [tag for tag in nt_tags.get_tags_by_taggee(contact)]})

Edit againt:

Logged what I'm passing and its

[<nt_tags.Tag object at 0x0000000005CAFF28>, <nt_tags.Tag object at 0x0000000005CAFFD0>]

Which looks like just a list not an iterator right?

1条回答
Animai°情兽
2楼-- · 2019-04-27 21:48

If tags is an iterator, then at the end of the first iteration, there won't be anything left to iterate. You could materialise it to a list before passing it to your template eg: list(tags) in your context...

查看更多
登录 后发表回答