Django 模板问题(访问列表)

2 投票
4 回答
13108 浏览
提问于 2025-04-16 06:21

我正在为我的第一个Django网站写一个模板。

我把一个字典列表传递给模板,另外还需要传递一些其他的列表,这些列表里存放的是布尔值(真或假)。(注意:所有的列表长度都是一样的)

这个模板大概长这样:

<html>
    <head><title>First page</title></head><body>
        {% for item in data_tables %}
        <table>
        <tbody>
                  <tr><td colspan="15">
                  {% if level_one_flags[forloop.counter-1] %}
                  <tr><td>Premier League
                  {% endif %}
                  <tr><td>Junior league
                  <tr><td>Member count
                  {% if level_two_flags[forloop.counter-1] %}
                  <tr><td>Ashtano League
                  {% endif %}
             </tbody>
        </table>
        {% endfor %}
  </body>
</html>

我遇到了以下错误:

模板错误

在模板 /mytemplate.html 中,第7行出错:无法解析剩余部分: '[forloop.counter-1]' 来自 'level_one_flags[forloop.counter-1]'

我并不惊讶会出现这个错误,因为我只是想看看这样做是否有效。到目前为止,从文档中我还没有找到如何通过索引来获取列表中的项目(也就是说,除了通过枚举)。

有没有人知道我该如何在模板中通过索引访问列表?

4 个回答

1

试着用“slice”来通过索引访问列表

http://docs.djangoproject.com/en/dev/ref/templates/builtins/#slice

7

简单来说,Django不支持你想要的功能。

在循环中,for循环有一些很有用的特性。

forloop.counter     The current iteration of the loop (1-indexed)
forloop.counter0    The current iteration of the loop (0-indexed)
forloop.revcounter  The number of iterations from the end of the loop (1-indexed)
forloop.revcounter0 The number of iterations from the end of the loop (0-indexed)
forloop.first       True if this is the first time through the loop
forloop.last        True if this is the last time through the loop
forloop.parentloop  For nested loops, this is the loop "above" the current one

你可以使用forloop.counter0来获取从零开始的索引,但不幸的是,Django的模板语言不支持用变量作为数组的索引(你可以这样写{{ foo.5 }},但不能这样写{{ foo.{{bar}} }})。

我通常会在视图中整理数据,这样在模板中展示起来会更简单。比如,你可以在视图中创建一个包含字典的数组,这样你只需要遍历这个数组,从每个字典中提取你需要的内容。对于特别复杂的情况,我甚至会创建一个DataRow对象,专门用来正确格式化表格中某一行的数据。

2

你可以使用点操作符来访问数组中的元素,或者说,做任何事情。

从技术上讲,当模板系统遇到一个点时,它会按照以下顺序进行查找:

* Dictionary lookup
* Attribute lookup
* Method call
* List-index lookup

我觉得你不能在索引上进行数学运算。你需要以其他方式构建你的数组,这样就不需要进行这种减法运算了。

撰写回答