Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
334 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 Reply

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 %}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...