开发者

Django - Sort the list into 3 columns on templates

开发者 https://www.devze.com 2023-03-06 10:07 出处:网络
My Models: Item: name desc order created_at And I got a list of items from Item like this: items = Item.objects.all().order_by(\'order\', \'-created_at\')

My Models:

Item:
    name
    desc
    order
    created_at

And I got a list of items from Item like this:

items = Item.objects.all().order_by('order', '-created_at')

Now I send this list into templates. But I have to sort it in a pattern. For examples:

<ul>
    <li>item 1</li>
    <li>item 2</li>
    <li>item 3</li>
</ul>
<ul>
    <li>item 4</li>
    <li>item 5</li>
    <li>item 6</li>
</ul>
<ul>
    <li>item 7</li>
</ul>

And with less items:

<ul>
    <li>item 1</li>
    <li>item 2</li>
</ul>
<ul>
    <li>item 3</li>
    <li>item 4</li>
</ul>
<ul>
    <li>item 5</li>
</ul>

or shortening:

<ul>
    <li>item 1</li>
</ul>
<ul>
    <li>item 2</li>
</ul>
<ul>
    <li>item 3</li>
</ul>

Any idea? Thanks for help!

UPDATE: add reflections

<ul>
    <li>item 1</li>
    <li>item 2</li>
</ul>
<ul>
    <li>item 3</li>
</ul>
<ul>
    <li></li>
</ul>

or

<ul>
    <li>item 1</li>
    <li>item 2</li>
    <li>item 3</li>
<开发者_开发知识库;/ul>
<ul>
    <li>item 4</li>
</ul>
<ul>
    <li>item 5</li>
</ul>

or

<ul>
    <li>item 1</li>
    <li>item 2</li>
    <li>item 3</li>
    <li>item 4</li>
</ul>
<ul>
    <li>item 5</li>
    <li>item 6</li>
</ul>
<ul>
    <li>item 7</li>
</ul>


Did you check the various snippets for partitioning lists?


I did this yesterday.

{% for link in footer_links %}
    {% if forloop.first or forloop.counter0|divisibleby:"6" %}
    <ul>
    {% endif %}
        <li><a href='{{ link.href }}'>{{ link.title }}</a></li>
    {% if forloop.last or forloop.counter|divisibleby:"6" %}
    </ul>
    {% endif %}
{% endfor %}

it doesn't quite do three columns, but it splits the links up into lists of a certain length (6)


I don't exactly understand the criteria that is determining your grouping - is it literally just cycling through by 3? If so, I think that the cycle template tag is what you are looking for:

http://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#cycle

0

精彩评论

暂无评论...
验证码 换一张
取 消