【问题标题】:How do I access groupList.i in a django for loop?如何在 django for 循环中访问 groupList.i?
【发布时间】:2011-08-14 22:14:26
【问题描述】:

我在模板内的 django 中创建了一个 for 循环。我有一个声明为groupList = ['superUsers', 'group1', 'group2', 'groupless'] 的名称列表。我可以通过说{{ groupList.2 }}(这输出group2)来呼叫组的各个成员。但是一旦我尝试在我的 for 循环中调用 {{ groupList.i }},就没有输出。我的代码如下所示:

{% for i in length|get_range %}
    {{ groupList.i }} <br /> <br />
    {% for staff in staffList.i %}
        {{staff}} <br /> <br />
    {% endfor  %}
{% endfor %}

长度定义为:length = len(groupList)

我希望能够显示第一个 grouplist 名称,然后是一个名称列表,然后是第二个 groupList 名称,然后是相应的名称列表。我做错了什么?

【问题讨论】:

    标签: html django for-loop


    【解决方案1】:

    尝试定义另一个模板变量为:

    foo = zip(groupList, staffList)
    

    并使用它:

    {% for group, staff in foo %}
        {{ group }}
        {{ staff }}
    {% endfor %}
    

    似乎是做你想做的最优雅的方式(恕我直言)

    【讨论】:

    • 你是对的。这正是我想要的。我实现了: {% for group, staff in foo %} {{ group }} {% for name in staff %} {{ name }} {% endfor %} 而且效果很好。非常感谢。
    【解决方案2】:

    试试类似this solution的东西

    以下是我将如何更改它以满足您的需求:

    {% for i in length|get_range %}
        {% with i as index %}
        {% with i|slugify|add:":"|add:i as subset %}
        {% with staffList|slice:subset as sublist %}
    
        <p>Previous item: {{ sublist.0 }}</p>
    
        {% endwith %}
        {% endwith %}
        {% endwith %}
    {% endfor %}
    

    所以这绝对不是一个优雅的解决方案,但是当我想使用计算值时,这就是我执行 set/list . 查找的方式。

    实际上,aviraldg 的解决方案要优雅得多,并且使用更好的方法来完成您想要具体完成的任务。

    【讨论】:

      猜你喜欢
      • 2016-02-12
      • 1970-01-01
      • 1970-01-01
      • 2017-11-06
      • 1970-01-01
      • 2020-04-14
      • 1970-01-01
      • 2021-09-08
      • 1970-01-01
      相关资源
      最近更新 更多