【问题标题】:How to index in Django Templates如何在 Django 模板中建立索引
【发布时间】:2020-06-24 14:01:22
【问题描述】:

我试图索引一个二维列表,例如,每当我访问members.0 时,定位工作得很好。但是我需要这个随着循环而改变,所以我创建了一个变量,但是,如果我要这样做 members.counter 这不会做任何事情。
有没有其他方法可以做到这一点,还是不可能?

  <tbody>
      {% for item in projects %}
      {% with counter=forloop.counter0 %}
      <tr>
        <td>{{ item }}</td>
        <td>{{ members.counter }}</td>
      </tr>
      {% endwith %}
      {% endfor %}
  </tbody>

【问题讨论】:

    标签: django templates jinja2


    【解决方案1】:

    如果需要access a list or dict at a specific position,可以使用方括号[]

    <tbody>
      {% for item in projects %}
        {% with counter=forloop.counter0 %}
          <tr>
            <td>{{ item }}</td>
            <td>{{ members[counter] }}</td>
          </tr>
        {% endwith %}
      {% endfor %}
    </tbody>
    

    【讨论】:

    • 是的,我已经尝试过了,但收到错误消息“无法解析余数:来自 'members[counter]' 的 '[counter]'”。我快速浏览了一下,但没有立即修复
    猜你喜欢
    • 2013-12-12
    • 1970-01-01
    • 2015-02-19
    • 1970-01-01
    • 2016-06-16
    • 2013-01-26
    • 2012-11-02
    • 2011-06-06
    • 1970-01-01
    相关资源
    最近更新 更多