我想在django模板中进行以下列表迭代:
foo = ['foo', 'bar'];
moo = ['moo', 'loo'];
for (a, b) in zip(foo, moo):
print a, b
django代码:
{%for a, b in zip(foo, moo)%}
{{a}}
{{b}}
{%endfor%}
尝试此操作时出现以下错误:
File "/base/python_lib/versions/third_party/django-0.96/django/template/defaulttags.py", line 538, in do_for
raise TemplateSyntaxError, "'for' statements should have either four or five words: %s" % token.contents
我如何做到这一点?
答案 0 :(得分:53)
您可以在视图中使用zip
:
mylist = zip(list1, list2)
return render(request, 'template.html', {'list': list, ... })
并在您的模板中使用
{% for item1, item2 in mylist %}
遍历两个列表。
这适用于所有版本的Django。
答案 1 :(得分:25)
只需将zip定义为template filter:
@register.filter(name='zip')
def zip_lists(a, b):
return zip(a, b)
然后,在您的模板中:
{%for a, b in first_list|zip:second_list %}
{{a}}
{{b}}
{%endfor%}
答案 2 :(得分:18)
可以做
{% for ab in mylist %}
{{ab.0}}
{{ab.1}}
{% endfor %}
但您无法在zip
结构中拨打for
。您必须先将压缩列表存储在另一个变量中,然后迭代它。
答案 3 :(得分:6)
我构建了django-multiforloop来解决这个问题。来自自述文件:
安装django-multiforloop后,渲染此模板
{% for x in x_list; y in y_list %}
{{ x }}:{{ y }}
{% endfor %}
有了这个背景
context = {
"x_list": ('one', 1, 'carrot'),
"y_list": ('two', 2, 'orange')
}
将输出
one:two
1:2
carrot:orange
答案 4 :(得分:2)
这里修改了{%for%} templatetag,它允许一次迭代迭代多个列表:
import re
from itertools import izip
from django import template
from django.template.base import TemplateSyntaxError
from django.template.defaulttags import ForNode
register = template.Library()
class ZipExpression(object):
def __init__(self, var):
self.var = var
def resolve(self, *args, **kwargs):
return izip(*(
f.resolve(*args, **kwargs) for f in self.var
))
@register.tag('for')
def do_for(parser, token):
"""
For tag with ziping multiple iterables.
"""
bits = token.contents.split()
if len(bits) < 4:
raise TemplateSyntaxError("'foreach' statements should have at least"
" four words: %s" % token.contents)
is_reversed = False
try:
in_index = bits.index('in')
sequence = bits[in_index+1:]
if sequence[-1] == 'reversed':
is_reversed = True
sequence.pop()
if not sequence or 'in' in sequence:
raise ValueError
sequence = re.split(r' *, *', ' '.join(sequence))
except ValueError:
raise TemplateSyntaxError(
"'foreach' statements should use the format"
" 'foreach a,b,(...) in x,y,(...)': %s" % token.contents)
loopvars = re.split(r' *, *', ' '.join(bits[1:in_index]))
for var in loopvars:
if not var or ' ' in var:
raise TemplateSyntaxError("'foreach' tag received an invalid"
" argumewnt: %s" % token.contents)
if len(sequence) > 1:
sequence = ZipExpression(map(parser.compile_filter, sequence))
else:
sequence = parser.compile_filter(sequence[0])
nodelist_loop = parser.parse(('empty', 'endfor',))
token = parser.next_token()
if token.contents == 'empty':
nodelist_empty = parser.parse(('endfor',))
parser.delete_first_token()
else:
nodelist_empty = None
return ForNode(
loopvars, sequence, is_reversed, nodelist_loop, nodelist_empty)
只需将其另存为模板标签库并将其导入模板即可。它将覆盖内置{%for%}标记(不要担心它向后兼容)。
使用示例:
{% for a,b in foo, moo %}
{{ a }}
{{ b }}
{% endfor %}
答案 5 :(得分:1)
您可以在服务器端创建moo对象的foo对象属性。
for f, b in zip(foo, bar):
f.foosBar = b
context = {
"foo": foo
}
当第二个列表是第一个列表的属性时(通常是这种情况),这个特别干净。
users = User.objects.all()
for user in users:
user.bestFriend = findBestFriendForUser(user)
context = {
"users": users
}
答案 6 :(得分:0)
在views.py中:
foo = ['foo', 'bar']
moo = ['moo', 'loo']
zipped_list = zip(foo,moo)
return render(request,"template.html",{"context":zipped_list}
在template.html中:
{% for f,m in context%}
{{f}}{{m}}
{% endfor %}
如果f
是从数据库返回的查询集,则可以通过{{f.required_attribute_name}}