2014-09-04 66 views
1

我有一個列表:一定數量的變量後更改列表輸出

c = [1,2,3,4,5,6,7,8] 
在我的模板

,我要輸出這個如下:

<table> 
    <tr> 
    <td>1</td> 
    <td>2</td> 
    <td>...</td> 
    </tr> 
</table> 

<table> 
    <tr> 
    <td>5</td> 
    <td>...</td> 
    <td>8</td> 
    </tr> 
</table> 

什麼是最好的方式做這個?

回答

2

如果你想使之更加通用的,你也可以使用內置的divisibleby標籤

{% for value in c %} 

    {% if forloop.counter0|divisibleby:cut_off %} 
     <table> 
      <tr> 
    {% endif %} 

    <td>{{value}}</td> 

    {% if forloop.counter|divisibleby:cut_off %} 
      </tr> 
     </table> 
    {% endif %} 

{% endfor %} 

其中c是列表和cut_off是分片號碼(例如,4在你的問題)。這些變量應該被髮送到您的視圖中的模板。

1

您可以使用slice模板過濾器:

<table> 
    <tr> 
    {% for value in c|slice:":4" %} 
     <td>{{ value }}</td> 
    {% endfor %} 
    </tr> 
</table> 

<table> 
    <tr> 
    {% for value in c|slice:"4:" %} 
     <td>{{ value }}</td> 
    {% endfor %} 
    </tr> 
</table> 

假設c在模板環境傳送。

slice基本上沿用了普通的Python slicing syntax

>>> c = [1,2,3,4,5,6,7,8] 
>>> c[:4] 
[1, 2, 3, 4] 
>>> c[4:] 
[5, 6, 7, 8]