使用forloop.counter值作为Django模板中的列表索引 [英] Using forloop.counter value as list index in a Django template

查看:130
本文介绍了使用forloop.counter值作为Django模板中的列表索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Django 1.1.1应用程序中,视图中有一个函数,该函数将一系列数字和项目列表返回给他的模板,例如:

in my Django 1.1.1 application I've got a function in the view that returns to his template a range of numbers and a list of lists of items, for example:

...  
data=[[item1 , item2, item3], [item4, item5, item6], [item7, item8, item9]]  
return render_to_response('page.html', {'data':data, 'cycle':range(0,len(data)-1])

在模板中,我有一个外部for循环,它还包含另一个for循环,以这种方式在输出中显示内部数据列表的内容

Inside the template I've got an external for loop, that contains also another for cycle to display in output the contains of the inner lists of data in this way

...  
{% for page in cycle %}   
...   
< table >   
{% for item in data.forloop.counter0 %}  
< tr >< td >{{item.a}} < /td > < td > {{item.b}} ... < /td > < /tr >  
...  
< /table >  
{% endfor %}  
{% if not forloop.last %}  
< div class="page_break_div" >  
{% endif %}  
{% endfor %}  
... 

但是Django模板引擎无法将 forloop.counter0 值用作列表的索引(相反,如果我手动将数字值用作索引,它会起作用).有没有一种方法可以让列表循环与外部 forloop.counter0 值一起使用?预先感谢您的帮助:)

But Django template engine doesn't work with the forloop.counter0 value as index for the list (instead it does if I manually put a numeric value as index). Is there a way to let the list loop works with the external forloop.counter0 value? Thanks in advance for the help :)

推荐答案

您不能将变量用于属性名称,字典键或列表索引.

You can't use variables for attribute names, dictionary keys or list indices.

range(0,len(data)-1] 也是无效的python,它应该是 range(len(data)).

Also range(0,len(data)-1] is not valid python. It should be range(len(data)).

您可能不需要 cycle .也许您想要的是这样:

You probably don't need cycle. Maybe what you want is this:

{% for itemlist in data %}
    ...
    <table>
        {% for item in itemlist %}
        <tr>
          <td>{{ item.a }}</td>
          <td>{{ item.b }} ... </td>
        </tr>
        ...
        {% endfor %}
    </table>
    {% if not forloop.last %}
        <div class="page_break_div">
    {% endif %}
{% endfor %}

这篇关于使用forloop.counter值作为Django模板中的列表索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆