2

I have a list of values I want to display in a template of django.

The list is more or less like this:

199801 string1
199802 string2
199904 string3
200003 string4
200011 string5

where the first column is a date in the form YYYYMM and the second is a generic string

the list is ordered by date desc

What I want to create is a list of stringx grouped by year something like this:

1998 string1, string2
1999 string3
2000 string4, string5

I gave a look to the documentation and I think the only thing I need is a way to create a variable where to store the "last year" I printed, so I can do something like:

if current_value.year != last_year
 #create a new row with the new year and the string
else
 #append the current string to the previous one

I think the only way I found is to write a custom templatetag and let it store the variable and the value... but before starting to write code I would like to know if there is a simpler way!

gruszczy
42.3k31 gold badges137 silver badges186 bronze badges
asked Jul 6, 2010 at 21:49
1
  • 3
    you should do it in view. from Django doc: the template system is meant to express presentation, not program logic. Commented Jul 6, 2010 at 22:06

3 Answers 3

5

Always do such thing in view, template system is not designed for such operations. Furthermore, it would be much harder to achieve this - the best idea that comes to my mind, is to create a filter. That, however, would be crazy - you would create a very specific filter just for one use. It's very easy to achieve in view:

last = None
result = []
for year, value in tuples:
 if year[0:4] == last:
 result[-1].append(value)
 else:
 result.append([value])
 last = year[0:4]
answered Jul 6, 2010 at 22:14

Comments

2

using itertools groupby

l = [
 (199801, 'string1'),
 (199802, 'string2'),
 (199904, 'string3'),
 (200003, 'string4'),
 (200011, 'string5'),
]
from itertools import groupby
iterator = groupby(l, key=lambda item: str(item[0])[:4])
for year, str_list in iterator:
 print year, list(str_list)

output

1998 [(199801, 'string1'), (199802, 'string2')]
1999 [(199904, 'string3')]
2000 [(200003, 'string4'), (200011, 'string5')]
answered Jul 7, 2010 at 5:03

1 Comment

Wow, this groupby iterator is great :-)
0

You can't create a variable in a view, by design.

However the ifchanged tag probably does what you want:

{% for val in values %}
 {% ifchanged val.0 %} {{val.0}} {% endifchanged %}
 {{ val.1 }}
{% endfor %}
answered Jul 7, 2010 at 6:29

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.