Breaking data into multiple display columns with D

2019-03-16 16:45发布

问题:

Overlap in terminology makes search for answers difficult for this one.

I'm looking for advice on the best way to implement a multiple-column display of my QuerySet that fills each column top to bottom over X columns. Meaning that the number of items in each column equals the QuerySet count divided by X (number of columns).

Using Offset doesn't work for this because I would like my data to grow into 4 columns without updating the offset manually. CSS floats work visually, but leave the data out of order.

回答1:

Something like that should work for you, pass the number of columns as columns to the template:

{% for item in items %}
    {% if forloop.first %}<div style="float:left;">{% endif %}
    {{ item }}
    {% if forloop.counter|divisibleby:columns %}
        </div><div style="float:left">
    {% endif %}
    {% if forloop.last %}</div>{% endif %}    
{% endfor %}
<div style="clear:both;"></div>


回答2:

It seems like lazerscience's answer is on the right track - but I think the OP wants the data to alphabetically sort the data down the column and then start back at the top of the next column. Using divisibleby: works to break the line after 'X' items, but I think it'll take a more complex template to do what the OP wants.

Not sure if it's possible, but in the view could you: Get item count, divide by 'columns' and used that # in Divisibleby to break into the next DIV column (the visual flow will be CSS)

As Lazers's example is now you're constructing Rows and then breaking it into columns, leaving the sort order across and then down.

Sorry if I missed something.

-K



回答3:

You'd better go and use a jQuery plugin to make some columns from a list.
Columnizer works very well for me



回答4:

Here are some django template filter that split a list into multiple sub-lists:

list partition template filters at djangosnippets.org

You could use these in a django template to split a long list into multiple columns as follows:

{% load list_tags %}
<h2>Some List</h2>

{% for sub_list in full_list|rows:"3" %}
<ul>
  {% for item in sub_list %}
    <li>
        {{item.name}}
    </li>
  {% endfor %}
</ul>
{% endfor %}

I included the template filters in my project in a file called list_tags.py. Adjust the {% load %} tag as necessary.