Django模板中的迭代列表 [英] Iterating lists in django template

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

问题描述

我有不同的列表

context = {
    'query' : request.POST['query'],
    'link' : link,
    'description' : description,
    'title' : title,
    'thumbnail' : thumb,
    'range' : range(len(title)),
}

我想遍历它们,例如:

for i in range(20):
    link[i]
    title[i]

在Django模板中.我该怎么办?

In django template. How can i do it?

推荐答案

通常,您通常不在视图中使用zip构造,然后在两个(或多个)迭代器上同时进行迭代:

You normally don't typically you use a zip construct in the view, and then iterate concurrently over both (or more) iterators:

context = {
    'query' : request.POST['query'],
    'linktitle' : zip(link, title),
    'description' : description,
    'thumbnail' : thumb,
    'range' : range(len(title)),
}

,然后在模板中:

{% for linki, titlei in linktitle %}
   {{ linki }} / {{ titlei }}
{% endfor %}

如果仅对前20个元素感兴趣,则可以在zip中添加range(20)或使用islice:

If you are only interested in the first 20 elements, you can add a range(20) in the zip, or use islice:

from itertools import islice

context = {
    'query' : request.POST['query'],
    'linktitle' : islice(zip(link, title), 20),
    'description' : description,
    'thumbnail' : thumb,
    'range' : range(len(title)),
}

这篇关于Django模板中的迭代列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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