2010-10-31 83 views
2

我正在为我的第一个Django网站编写模板。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]'

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

有谁知道我可以通过模板中的索引访问列表?

回答

2

您可以使用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 

我不相信你可以对指数做数学。你必须传入以其他方式构造的数组,以便不必进行这种减法。

+0

嗯,Django开发人员似乎觉得这很愚蠢,因为循环迭代和序列索引有不同的基础。我敢肯定,我的做法是错误的。尽管如此,至少,由于您的信息,我可以访问该项目 - 只是索引是错误的。我将不得不从循环结构中找到正确的基于零的索引。 – skyeagle 2010-10-31 15:36:15

+1

存在'counter0'。看到这里:http://docs.djangoproject。com/en/dev/ref/templates/builtins /#对于 – 2010-10-31 16:16:20

+0

感谢Nick。我会记得下次使用这个(counter0) - 我知道django开发者不会留下类似的东西:)。 – skyeagle 2010-10-31 21:52:01

0

也许更好的方法是使用forloop.last。当然,这需要你发送给特定level_one_flaglevel_two_flag出level_one_flags和level_two_flags阵列的模板,但我认为这个解决方案保存视图和模板之间更好的逻辑分离:

<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> 
6

访问列表总之,你想要什么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对象,它可以正确格式化表中特定行的数据。