Account Options

  1. Sign in
Google Groups Home
« Groups Home
Message from discussion making two-column table from one-column data
The group you are posting to is a Usenet group. Messages posted to this group will make your email address visible to anyone on the Internet.
Your reply message has not been sent.
Your post was successful
 
From:
To:
Cc:
Followup To:
Add Cc | Add Followup-to | Edit Subject
Subject:
Validation:
For verification purposes please type the characters you see in the picture below or the numbers you hear by clicking the accessibility icon. Listen and type the numbers you hear
 
Ned Batchelder  
View profile  
 More options Dec 2 2007, 12:59 pm
From: Ned Batchelder <n...@nedbatchelder.com>
Date: Sun, 02 Dec 2007 12:59:37 -0500
Local: Sun, Dec 2 2007 12:59 pm
Subject: Re: making two-column table from one-column data
If your data is in the 'data' context variable, then try this:

        <table>
        {% for d in data %}
            {% if forloop.counter0|divisibleby:"2" %}<tr>{% endif %}
            <td>{{d}}</td>
            {% if forloop.counter|divisibleby:"2" %}</tr>{% endif %}
        {% endfor %}
        {% if data|length|divisibleby:"2" %}{% else
%}<td>&nbsp;</td></tr>{% endif %}
        </table>

It's a little awkward, and doesn't generalize to more than two columns,
but it does produce properly structured HTML.

If you're willing to add some code to your view, you can get more columns:

In the view:

    context['data'] = data
    ncols = 3
    for i, d in enumerate(data):
        d.firstcol = (i % ncols == 0)
        d.lastcol = (i % ncols == ncols-1)
    context['data_blanks'] = [None]*((ncols-len(data)%ncols)%ncols)

In the template:

        <table>
        {% for d in data %}
            {% if d.firstcol %}<tr>{% endif %}
            <td>{{d}}</td>
            {% if d.lastcol %}</tr>{% endif %}
        {% endfor %}
        {% for blank in data_blanks %}<td>&nbsp;</td>{% endfor %}
        {% if data_blanks %}</tr>{% endif %}
        </table>

--Ned.
http://nedbatchelder.com

andrej kesely wrote:
> hi,
> i have small question:
> suppose i have data in QuerySet - ['A', 'B', 'C', 'D', 'E', 'F',
> 'G'].
> I want make from this set two-column table in my template:

>   A    B
>   C    D
>   E    F
>   G

> What is the fastest way to do it? I don't want split the QuerySet in
> my views to something like this: [(A, B), (C, D)...] etc.

> Thanks,
> Andrej Kesely

--
Ned Batchelder, http://nedbatchelder.com

 
You must Sign in before you can post messages.
To post a message you must first join this group.
Please update your nickname on the subscription settings page before posting.
You do not have the permission required to post.