ForLoop迭代作为Django模板中的列表索引 [英] ForLoop Iterations as List Index in Django Template

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

问题描述

我正在构建一个django网页,但是我似乎遇到了麻烦,因为我无法真正弄清楚如何将for循环的当前迭代(在模板中)用于多个列表:

I'm building a django webpage but I seem to have hit a snag as I can't really figure out how to use the current iteration of a for loop (in the template) for multiple lists:

        {% for num in loopRange %}
    <tr>
        {% for num2 in subRange %}
        <td>{% cycle list1 list2 list3 list4 %}</td>
        {% endfor %}
    </tr>
    {% endfor %}

我在这里的stackoverflow中发现了两个类似的问题,我尝试使用循环,但是可惜这只是导致列表中的所有成员每次都被打印出来-并非完全出乎意料,但我不知道该怎么做.我的生活.

I found a couple questions here stackoverflow that were similar and I attempted to use cycle, but alas this just resulted in all members of the list being printed each time--not exactly unexpected but I can't figure out how for the life of me.

我所拥有的是多个内容相似的列表,每个列表都是一行中的一列.因此,如果它是python,而我正在连接字符串,它将是这样的:

What I have is multiple lists that are all similar in content, each list is a column in a row. So, if it was python and I was concatenating strings it would be like this:

for i in xrange(5):
    string = list1[i] + list2[i] + list3[i] + list 4[i]

基本上就是这样.除了两个xrange(在第一个示例中为loopRange和Subrange)之外,我还将每个列表作为上下文传递给我,我需要五行(每个列表有五个成员)和四列(四个列表).

So basically that. I'm passing each list in as context in addition to two xranges (loopRange and Subrange in the first example), I need five rows (each list has five members) and four columns (four lists).

我想简而言之,我想将列表索引称为foo [bar],在Django中将其称为foo.bar,但是bar显然不能是作为内容传递的可迭代范围的整数

I suppose in a nuthshell I want to refer to list indeces as foo[bar], done in django as foo.bar, however bar apparently can't be an integer an iterable range passed in as content

谢谢!

推荐答案

我会说最好的方法是在将视图中的数据传递给模板之前对其进行处理.

I'd say that the best approach would be to work on the data in the view before passing it to the template.

例如,内置的zip可用于基于包含列的列表创建行列表:

For example, the zip builtin can be used to create the rows list based on the lists that contain the columns:

rows = zip(list1, list2, list3, list4)

此后,模板可以逐行遍历行,并在需要时使用索引访问来访问列:

After that, the template can iterate over the rows one by one and access the columns using index access if needed:

{% for row in rows %}
  {{row.0}} {{row.1}} {{row.2}} {{row.3}}
{% endfor %}

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

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