I have an odd problem with Django. I have a set of objects that Im looping through in a template as you would normally. However, I need to group the items in threes. The layout of the page goes like this:
Painting 1 – Painting 2 – Painting 3
D E S C R I P T I O N 1
D E S C R I P T I O N 2
D E S C R I P T I O N 3
Painting 4 – Painting – 5 Painting 6
D E S C R I P T I O N 4
D E S C R I P T I O N 5
D E S C R I P T I O N 6
etc etc
I cant quite figure out the best set of Django tags to do this really. It seems somewhat tricky. the {% cycle %} statement didnt quite help.
Unless of course, I do some java script hacking of some kind and leave Django out of this? There must be someway of saying “Put all the description divs after one another” or similar. Not sure how best to play with this ordering. Any thoughts? Cheers.
Whenever you find yourself trying out complex code inside templates, its usually a good indication that it should be moved elsewhere. One of the alternative solutions have already been suggested, which is to move the code into your view function.
The other solution would be to expose the functionality via a new template tag. One of the reasons you would choose this solution over the view solution, is that you’ll be able to easily re-use the code for pages that are served with different views.
In template code you would use it like this: