Home Django- template loop but exclude repeats
Reply: 1

Django- template loop but exclude repeats

NewToJS
1#
NewToJS Published in 2018-01-12 03:09:53Z

Say I have this data and I'm passing to my template:

apps = [
 {'category': 'one', 'item': 'blah'},
 {'category': 'one', 'item': 'blah'},
 {'category': 'two', 'item': 'blah'},
 {'category': 'two', 'item': 'blah'},
 {'category': 'three', 'item': 'blah'}
]

Then in my template I want to add one div withe the id 'category' but not repeat any divs if they've been added before with the id. So something similar to:

{% for app in apps %}
   <div id="{{app.category}}"></div>
{% endfor %}

But I only want these to be rendered:

<div id="one"></div>
<div id="two"></div>
<div id="three"></div>
seuling
2#
seuling Reply to 2018-01-13 07:32:46Z

I think you should remove duplicates before pass your apps list to template.

There's plenty of ways to do so, and I'll give simple example.

apps = [dict(t) for t in set([tuple(d.items()) for d in apps])]

Update

If you want to del your {'items': 'blah'} in apps, I recommend del that key, value pair before making new apps.

You can just use simple del function with for loop like this

for d in apps:
    del d['item']

then your apps list will be like this

[{'category': 'one'},
 {'category': 'one'},
 {'category': 'two'},
 {'category': 'two'},
 {'category': 'three'}]

Then you can use my answer again.

If you are familiar with lambda, you can use lambda function like this

map(lambda d: d.pop('item'), apps)

And you will get same apps as above.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.332218 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO