【问题标题】:Django: How to iterate over two lists inside template [duplicate]Django:如何遍历模板内的两个列表[重复]
【发布时间】:2023-03-06 14:19:02
【问题描述】:

从 views.py 我发送到模板 2 数组:

  1. 动物:['cat','dog','mause']
  2. 多少:['one','two','three']

模板:

{% for value in animal %}
    animal:{{ value }}  \ how meny  {{ how_many[(forloop.counter0)]  }}
{% endfor %} 

在 for 循环中,我想读取一个迭代,然后在第二个数组中使用它,但我无法让它工作。我是初学者。

【问题讨论】:

  • 别这样,从views.py发送zip(animal, how_many)

标签: python django


【解决方案1】:

根据文档,you can't do that straightforward

请注意,如果模板上下文中存在变量“bar”,则 {{ foo.bar }} 等模板表达式中的“bar”将被解释为文字字符串,而不使用变量“bar”的值。

我建议您将zip(animal, how_many) 添加到模板的上下文中:

context['animals_data'] = zip(animal, how_many)

然后您可以访问这两个列表:

{% for animal, how_many in animals_data %}
    {{ animal }} {{ how_many }}
{% endfor %}

【讨论】:

  • 收到此错误“上下文必须是 dict 而不是 zip。”
【解决方案2】:

试试这个:

animal = ['cat','dog','mause']
how_many = ['one','two','three']
data = zip(animal,how_many)
return render_to_response('your template', {'data': data})

在模板中

{% for i,j in data %}
{{i}}   {{j}}
{% endfor %}

【讨论】:

    【解决方案3】:

    我建议为这个问题编写你自己的模板标签。将以下内容(来自this SO question)放入名为 index 的模板中,该模板应保存在 templatetags/index.py 中:

    from django import template
    register = template.Library()
    
    @register.filter
    def index(List, i):
        return List[int(i)]
    

    现在,加载和使用它应该很简单:

    {% load index %}
    {% for value in animal %}
      animal:{{ value }}  \ how meny {{ how_meny|index:forloop.counter0 }}
    {% endfor %}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-25
      • 1970-01-01
      • 1970-01-01
      • 2011-05-15
      • 1970-01-01
      • 2010-10-21
      • 1970-01-01
      • 2018-02-24
      相关资源
      最近更新 更多