遍历两个列表的Django模板语法

2024-04-23 11:16:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我有下面的django模板,当我迭代一个列表(class_list_overall)时,我想使用forloop.counter0作为另一个列表(classTimeSlots)中的索引。它总是给我一个TemplateSyntaxError。我尝试过以下变化:

  1. {{classTimeSlots.{{forloop.counter0}}}}
  2. {{classTimeSlots.[forloop.counter0]}}
  3. {{classTimeSlots.{forloop.counter0}}}
  4. {{classTimeSlots.(forloop.counter0)}}
  5. {{classTimeSlots.forloop.counter0}}
  6. {% with forloop.counter0 as index%} <legend>{{ classTimeSlots.index}}</legend> {% endwith %}

这些都不管用。有什么建议吗?我只是DJango的新手。我在用谷歌应用引擎。在

以下是代码片段(我知道它效率低下,但我尝试了不同的方法):

{% for class_list in class_list_overall %}
    <fieldset> <legend>{{ classTimeSlots.forloop.counter0 }}</legend>
        <ul>
            <li> <label>First Choice </label>
                <select class="dropdown" name="class{{forloop.counter}}1" size="1">
                    <option value="Click Here to Choose" selected="selected">Click Here to Choose</option>
                    {% for class in class_list %}
                        <option>{{class}}</option>
                    {% endfor %}
                </select>
            </li>
            <li> 
                <label>Second Choice </label>
                <select class="dropdown" name="class{{forloop.counter}}2" size="1">
                    <option value="Click Here to Choose" selected="selected">Click Here to Choose</option>
                    {% for class in class_list %}
                        <option>{{class}}</option>
                    {% endfor %}
                </select>
            </li>
        </ul>
    </fieldset>
{% endfor %}

Tags: tohereliselectlabellistclassclick
3条回答

可能但不建议:

{% for class_list in class_list_overall %}
<fieldset> <legend>
   {% for cts in classTimeSlots %}
    {% ifequal forloop.counter forloop.parentloop.counter %} {{cts}} 
    {% endifequal %} 
   {% endfor %} </legend>
    <ul>
        <li> <label>First Choice </label>
            <select class="dropdown" name="class{{forloop.counter}}1" size="1">
                <option value="Click Here to Choose" selected="selected">Click Here to Choose</option>
                {% for class in class_list %}
                    <option>{{class}}</option>
                {% endfor %}
            </select>
        </li>
        <li> 
            <label>Second Choice </label>
            <select class="dropdown" name="class{{forloop.counter}}2" size="1">
                <option value="Click Here to Choose" selected="selected">Click Here to Choose</option>
                {% for class in class_list %}
                    <option>{{class}}</option>
                {% endfor %}
            </select>
        </li>
    </ul>
</fieldset>{% endfor %}

但最好将列表纳入父字典:

^{pr2}$

然后将上述代码改为:

<legend>
   {{ class_list.label }}
</legend>

简而言之:你不能这么做。在

模板语言不会尝试确定以点语法传递的变量的值。在

它将执行forloop.counter0的文本查找

1:编写一个接受变量和键的模板标记,并让它返回variable[key]

2:很有可能在视图中完成。我能看看吗?在

Django不支持这一点——这是故意限制的。相反,您应该修改view函数,将这两个列表一起zip,并将其传递给模板。在

相关问题 更多 >