开发者

Concatenating two variables in Django that are being rendered via a template

Semi-brief overview...

--- Indices is a Python list of indices that correspond to the total number of rows the HTML table will have. For example if the column has 5 rows the list would be [0, 1, 2, 3, 4].

--- RowNames is a Python list of the individual names of the HTML table rows. For example [Title, Year, Author, Date, State]

--- ColData is the data that will fill the HTML's tables columns corresponding to the rows. For example ["Great Scott", 1989, "James Bixby", "12-4-2011", "MA"]

Here is what I need to do...

{% for Index in Indices %} 
       <tr>
             <td width='11%' align='right'><strong>{{ RowNames.I开发者_如何转开发ndex }}</strong></td>   
             <td width='89%' align='left'>{{ ColData.Index }}</td>      
      </tr>             
{% endfor %}     

However, Django does not interpret {{ RowNames.Index }} or {{ ColData.Index }} as the ith element of the list. How can I re-code what I have above so it is interpreted as the ith element of the list?

Thanks in advance.


You can access the index of the element via forloop.counter0 (see here).

Ok, I remembered wrong. Basically you should approach the problem like this: either create list of objects or a list of tuples. Django does not support this for reason - the programming should not be done in the templates.

Using python's zip() function you can create a list of tuples with the following form: [(rowname, coldata), (rowname, coldata)...]

mydata = zip(rowname_list, coldata_list)

Now in your template you can iterate over each rowname and coldata like this:

{% for rowname,coldata in mydata %}
<tr>
    <td width='11%' align='right'><strong>{{ rowname }}</strong></td>   
    <td width='89%' align='left'>{{ coldata }}</td>      
</tr>  
{% endfor %}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜