thumbtackthief
thumbtackthief

Reputation: 6211

Organize table data by columns

I have a django template that passes in two lists of varying sizes (but at least one item each). I'm trying to display this data in a table so it looks like this:

List A | List B
-------------------
A - 1  | B - 1
A - 2  | B - 2
A - 3  | 
A - 4  |

(The empty cells in B could be empty, or something like '--')

I'm not sure how to go about doing this. Am I missing something obvious?

(Note: I'm not the one who wants this as a table; I had it as two nice lists and it looked perfect, but I was overruled--I'm stuck with a table.)

EDIT:
So I'm iterating over each list with a django for loop. I'm looking for something like this:

<table>
  <tr>
    <th>List A</th>
    <th>List B</th>
  </tr>

#first column
{% for person in listA %}
  <td>person</td>
{% endfor %}

#second column

{% for person in listB %}
  <td>person</td>
{% endfor %}
</table>

Upvotes: 1

Views: 176

Answers (2)

Alvaro
Alvaro

Reputation: 12037

Here's the full answer: First, let's fix the context:

if len(a) <= len(b):
    a += ['-', ] * (len(b) - len(a))
else:
    b += ['-', ] * (len(a) - len(b))

my_composite_list = zip(a, b)

EDIT: - You can use itertools for this -

my_composite_list = izip_longest(a, b)

And we pass it to the context.

Then, in the template:

<table>
    <thead>
        <tr>
            <th>List A</th>
            <th>List B</th>
        </tr>
    </thead>
    <tbody>
        {% for a, b in my_composite_list %}
            <tr>
                 <td>{{ a }}</td><td>{{ b }}</td>
            </tr>              
        {% endfor %}
    </tbody>
</table>

Upvotes: 0

Mario C&#233;sar
Mario C&#233;sar

Reputation: 3737

In your context define records using izip_longest to zip both lists.

from itertools import izip_longest

listA = [1, 2, 3, 4]
listB = [1, 2, '--']

records = izip_longest(listA, listB)
# will return [(1, 1), (2, 2), (3, '--'), (4, None)]

Later on your template do.

<table>
    <tr>
        <th>Col1</th>
        <th>Col2</th>
    <tr>
    {% for col1, col2 in records %}
    <tr>
        <td>{{col1}}</td>
        <td>{{col2}}</td>
    <tr>
    {% endfor %}
</table>

See it working here http://djangotemplator.appspot.com/t/68342edf5d964872a0743a6a6183ef56/

Upvotes: 3

Related Questions