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
1.0k views
in Technique[技术] by (71.8m points)

django template to populate bootstrap rows and columns

So here's my problem: I've got a bunch of instances of a class. I would like to have a sort of table of these instance objects, so that there is a maximum of six in every row. In bootstrap terms, I would like each object to be represented by a thumbnail in a "div" of class "span2".

My initial impulse was to use a nested for loop, but I am having trouble manipulating my index variable in the template, and I can't figure out how to do so outside of my template.

Here is generally what the python/django template/pseudo code is I'm trying to figure out.

queryset = Class.objects.all()
set_length = queryset.count()

num_rows = set_length/6 
#because I want 6 columns in each row, each with one instance

set_as_list = list(queryset) 
# have a list so I can iterate through objects by index

for i in range(table_rows):
    # make a row
    <div class="row">
    for j in range (i*6,(i+1)*6):
        #make six or less columns
        <div class="span2">
           <p>set_as_list[j].attribute1</p>
           <p>set_as_list[j].attribute2</p>
        </div>
    </div> # end row

I hope this flagrant mixing of django templating language, python, and html doesn't offend anybody too badly. just trying to express the idea of what I'm trying to do. I would appreciate any help someone may be willing to offer because I've been struggling with this for days and have done quite a bit of searching for a solution both within a template and outside.

I also realise that there will be need to be a final row with the remainder of objects after the integer division.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Have no time to explain, but I've had similar problem and until i closed this browser page here is a solution

{% for sub_article in articles %}
    {% if forloop.first %}<div class="row">{% endif %}
    <div class="col-xs-4">
            <a href="#">
                {{ sub_article.name }}
            </a>
        </div>
    {% if forloop.counter|divisibleby:3 %}</div><div class="row">{% endif %}
    {% if forloop.last %}</div>{% endif %}
{% endfor %}

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

...