Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
331 views
in Technique[技术] by (71.8m points)

css - Django templates: Group items in Threes

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use a simple filter for this:

import itertools

from django import template

register = template.Library()

@register.filter
def chunks(value, chunk_length):
    """
    Breaks a list up into a list of lists of size <chunk_length>
    """
    clen = int(chunk_length)
    i = iter(value)
    while True:
        chunk = list(itertools.islice(i, clen))
        if chunk:
            yield chunk
        else:
            break

Then inside your template:

{% for chunk in paintings|chunks:3 %}
  <div class="row">
    {% for painting in chunk %}
      <div>{{ painting }}</div>
    {% endfor %}
  </div>
{% endfor %}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...