2014-01-14 78 views
1

我有一个django模板,它传入两个不同大小的列表(但每个至少有一个项目)。我想在一个表格中显示这个数据,所以它看起来是这样的:按列组织表数据

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

(空细胞,B可以是空的,或者类似的东西“ - ”)

我不是确定如何去做这件事。我错过了明显的东西吗?

(注:我不是谁想要这是一个表中的一个;我是有两个漂亮的列表和它看起来完美,但我被否决 - 我坚持了一个表)

编辑:
所以我用django循环迭代每个列表。我正在寻找这样的事情:

<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> 
+1

不知道什么? HTML?清单?模板语言? – Alvaro

+0

的HTML。编辑 - 请让我知道如果仍然不清楚。 – thumbtackthief

回答

3

在你的上下文中定义records使用izip_longest压缩这两个列表。

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)] 

稍后在您的模板上做。

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

看到它在这里工作http://djangotemplator.appspot.com/t/68342edf5d964872a0743a6a6183ef56/

+0

Django templator的+1。非常有用的链接。 – IanAuld

+0

太棒了!谢谢! Templator也非常有帮助! – thumbtackthief

0

下面是完整的答案: 首先,让我们来解决的背景下:

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

my_composite_list = zip(a, b) 

编辑: - 您可以使用itertools这个 -

my_composite_list = izip_longest(a, b) 

我们将其传递给上下文。

然后,在模板:

<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>