django 模板问题(访问列表) [英] django template question (accessing a list)

查看:32
本文介绍了django 模板问题(访问列表)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我的第一个 django 网站编写模板.

I am writing a template for my first django website.

我将字典列表传递给变量中的模板.我还需要传递一些其他包含布尔标志的列表.(注意:所有列表的长度相同)

I am passing a list of dictionaries to the template in a variable. I also need to pass a few other lists which hold boolean flags. (Note: all lists have the same length)

模板看起来像这样:

<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]'

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

我对收到此错误并不感到惊讶,因为我只是想看看是否可行.到目前为止,从文档中,我还没有找到如何通过索引(即通过枚举以外的方式)获取列表中的项目.

I am, not suprised I am getting this error, since I was just trying to see if would work. So far, from the documentation, I have not found out how to obtain the items in a list by index (i.e. other than by enumeration).

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

Does anyone know how I may access a list by index in a template?

推荐答案

您使用 点运算符来索引数组,或者,实际上,做任何事情.

You use the dot-operator to index the array, or, really, to do anything.

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

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

我不相信您可以对索引进行数学运算.您必须传入以其他方式构造的数组,这样您就不必进行此减法.

I don't believe you can do math on the index. You'll have to pass in your array constructed in some other way so that you don't have to do this subtraction.

这篇关于django 模板问题(访问列表)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆