Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate over the same list twice in Jinja2?

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?

like image 422
Joren Avatar asked Nov 30 '12 19:11

Joren


1 Answers

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

like image 122
Jon Clements Avatar answered Sep 24 '22 05:09

Jon Clements