anhtran
anhtran

Reputation: 2044

Django - Sort the list into 3 columns on templates

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>

Upvotes: 3

Views: 2084

Answers (3)

Glycerine
Glycerine

Reputation: 7347

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)

Upvotes: 2

arie
arie

Reputation: 18982

Did you check the various snippets for partitioning lists?

Upvotes: 2

jMyles
jMyles

Reputation: 12172

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

Upvotes: 0

Related Questions