Django模板问题(访问列表)

2024-04-26 05:12:48 发布

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

我正在为我的第一个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>

我得到以下错误:

Template error

In template /mytemplate.html, error at line 7 Could not parse the remainder: '[forloop.counter-1]' from 'level_one_flags[forloop.counter-1]'

我是,不惊讶我得到这个错误,因为我只是想看看是否会工作。到目前为止,从文档中,我还没有找到如何通过索引(即,不是通过枚举)获取列表中的项。

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


Tags: 模板列表iftitlehtmlcountertablebody
3条回答

简言之,Django不会做你想做的事。

for loop在循环中有许多有用的属性。

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}} }})。

我通常做的是尝试在视图中排列数据,使其更易于在模板中显示。例如,您可以在由字典组成的视图中创建一个数组,这样您只需循环遍历该数组,并从各个字典中准确地提取所需的内容。对于非常复杂的事情,我已经创建了一个data row对象,它可以正确地格式化表中特定行的数据。

尝试使用“slice”按索引访问列表

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

您可以使用dot-operator索引数组,或者,实际上,执行任何操作。

Technically, when the template system encounters a dot, it tries the following lookups, in this order:

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

我不相信你能在索引上做数学题。您必须传入以其他方式构造的数组,这样就不必执行此减法。

相关问题 更多 >