【问题标题】:Using forloop.counter value as list index in a Django template在 Django 模板中使用 forloop.counter 值作为列表索引
【发布时间】:2011-01-30 21:31:08
【问题描述】:

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

...  
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 循环,以这种方式在输出中显示内部数据列表的包含

...  
{% 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 值一起使用? 提前感谢您的帮助:)

【问题讨论】:

    标签: django list templates for-loop django-templates


    【解决方案1】:

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

    另外range(0,len(data)-1] 不是有效的python。应该是range(len(data))

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

    {% 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 %}
    

    【讨论】:

    • 感谢 Stefanw,这正是我想要做的,我没有考虑遍历列表,因为在 len(data)==1 的情况下(是的,我之前写的不是好的 python 语句)我必须以不同的方式显示列表输出。无论如何,现在看来一切正常,再次感谢您的帮助!
    • 这绝对是正确的方法,但here 是我解决“没有变量作为属性名称、字典键或列表索引”问题的方法。可以肯定的是不优雅,但它只使用内置标签和过滤器。
    【解决方案2】:

    我以一种相当低效的方式解决了这个问题。阅读此代码时,请不要在计算机上呕吐。给定两个长度相同的列表,它将遍历第一个并从第二个打印相应的项目。

    如果您必须使用它,请仅将其用于很少访问的模板,其中两个列表的长度都很小。理想情况下,重构模板的数据可以完全避免这个问题。

    {% for list1item in list1 %}
       {% for list2item in list2 %}
          {% if forloop.counter == forloop.parentloop.counter %}
              {{ list1item }} {{ list2item }}
          {% endif %}
       {% endfor %}
    {% endfor %}
    

    【讨论】:

    • 我真的无法想象这是最好的解决方案。
    • 这是我案例的最佳答案。我希望我有双倍按钮
    【解决方案3】:

    我想通过传递一个切换 True/False 值的列表,在我的表格中使用样式表交替显示颜色。我发现这真的很令人沮丧。最后,我创建了一个字典项列表,其键与表中的字段相同,再加上一个带有切换真/假值的条目。

    def jobListView(request):
        # django does not allow you to append stuff to the job identity, neither
        # will it allow forloop.counter to index another list. The only solution
        # is to have the toggle embedded in a dictionary along with
        # every field from the job
        j                   = job.objects.order_by('-priority')
        # have a toggling true/false list for alternating colours in the table
        theTog              = True
        jobList             = [] 
        for i in j:
            myJob           = {}
            myJob['id']     = i.id
            myJob['duty']   = i.duty
            myJob['updated'] = i.updated
            myJob['priority'] = i.priority
            myJob['description'] = i.description
            myJob['toggle'] = theTog
            jobList.append(myJob)
            theTog          = not(theTog)
        # next i
    
        return render_to_response('index.html', locals())
    # end jobDetaiView
    

    还有我的模板

    {% if jobList %}
        <table border="1"><tr>
        <th>Job ID</th><th>Duty</th><th>Updated</th><th>Priority</th><th>Description</th>
        </tr>
    
        {% for myJob in jobList %}
    
            <!-- only show jobs that are not closed and have a positive priority. -->
            {% if myJob.priority and not myJob.closeDate %}
                <!-- alternate colours with the classes defined in the style sheet -->
                {% if myJob.toggle %}
                    <tr class=d1> 
                {% else %}
                    <tr class=d0>
                {% endif %}
    
                <td><a href="/jobs/{{ myJob.id }}/">{{ myJob.id }}</td><td>{{ myJob.duty }}</td> 
                <td>{{ myJob.updated }}</td><td>{{ myJob.priority }}</td>
                <td class=middle>{{ myJob.description }}</td>
                </tr>
            {% endif %}
        {% endfor %}
        </ul>
    {% else %}
        <p>No jobs are in the system.</p>
    {% endif %}
    

    【讨论】:

      【解决方案4】:

      使用 forloop.last - 如果这是最后一次循环,则为真:

      {% if forloop.last %}
      {% endif %}
      

      来自Built-in template tags and filters

      【讨论】:

        猜你喜欢
        • 2014-07-23
        • 2019-02-26
        • 2021-07-23
        • 2019-04-16
        • 2010-11-16
        • 1970-01-01
        • 2011-06-06
        • 2012-07-04
        • 1970-01-01
        相关资源
        最近更新 更多