django模板问题(访问列表)

时间:2010-10-31 14:36:24

标签: python django django-templates

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

答案 0 :(得分:7)

简而言之,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}} }})。

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

答案 1 :(得分:2)

您使用dot-operator索引数组,或者,实际上是做任何事情。

  

从技术上讲,当模板系统   遇到一个点,它尝试了   按照以下顺序查找:

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

我不相信你可以对索引做数学。你必须传递以其他方式构造的数组,这样你就不必进行这种减法。

答案 2 :(得分:1)

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

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

答案 3 :(得分:0)

也许更好的方法是使用forloop.last。当然,这将要求您从level_one_flags和level_two_flags数组中向模板发送特定的level_one_flaglevel_two_flag,但我认为此解决方案在视图和模板之间保持更好的逻辑分离:

<html>
    <head><title>First page</title></head><body>
    {% for item in data_tables %}
    <table>
    <tbody>
              <tr><td colspan="15">
              {% if forloop.last and level_one_flag %}
              <tr><td>Premier League
              {% endif %}
              <tr><td>Junior league
              <tr><td>Member count
              {% if forloop.last and level_two_flag %}
              <tr><td>Ashtano League
              {% endif %}
         </tbody>
    </table>
    {% endfor %}
    </body>
</html>
相关问题