context ={
"items":Items.objects.all(),
"item_pics":Item_pics.objects.all(),
}
return render(request, 'menu/items.html', context)
item_pics = [[{'item_id': 1, 'is_front': False, 'url': 'url_to_the_image1'},
{'item_id': 1, 'is_front': False, 'url': 'url_to_the_image2'},
{'item_id': 1, 'is_front': False, 'url': 'url_to_the_image3'},
{'item_id': 1, 'is_front': False, 'url': 'url_to_the_image4'},
{'item_id': 1, 'is_front': True, 'url': 'url_to_the_image5'},
{'item_id': 1, 'is_front': True, 'url': 'url_to_the_image6'},
{'item_id': 1, 'is_front': True, 'url': 'url_to_the_image7'},
{'item_id': 1, 'is_front': True, 'url': 'url_to_the_image8'},
{'item_id': 1, 'is_front': True, 'url': 'url_to_the_image9'}],
[{'item_id': 2, 'is_front': False, 'url': 'url_to_the_image1'},
{'item_id': 2, 'is_front': False, 'url': 'url_to_the_image2'},
{'item_id': 2, 'is_front': False, 'url': 'url_to_the_image3'},
{'item_id': 2, 'is_front': False, 'url': 'url_to_the_image4'},
{'item_id': 2, 'is_front': False, 'url': 'url_to_the_image5'},
{'item_id': 2, 'is_front': False, 'url': 'url_to_the_image6'},
{'item_id': 2, 'is_front': False, 'url': 'url_to_the_image7'},
{'item_id': 2, 'is_front': False, 'url': 'url_to_the_image8'},
{'item_id': 2, 'is_front': False, 'url': 'url_to_the_image9'}]
]
{% for pic in item_pics %}
{% if pic.is_front %}
<img src="{{ pic.url }}">
{% endif %}
{% endfor %}
如何选择pic.is_front == True
的第一次出现然后停止for循环
如果对于pic.is_fron = False
的每张图片item_pics
,我想选择item_pics
的第一张照片
for pics in item_pics:
found = False
for pic in pics:
if pic['is_front'] == True and found == False:
print(pic['item_id'], pic['url'])
found = True
if found == False:
print(pics[0]['item_id'], pics[0]['url'])
答案 0 :(得分:3)
最好在python代码中完成-在视图本身中,或者,如果不可能的话,使用custom template filter。
在视图中
item_pics = [{'item_id': 1, 'is_front': False, 'url': 'url_to_the_image'},
{'item_id': 1, 'is_front': False, 'url': 'url_to_the_image'},
{'item_id': 1, 'is_front': False, 'url': 'url_to_the_image'}
{'item_id': 1, 'is_front': False, 'url': 'url_to_the_image'}
{'item_id': 1, 'is_front': True, 'url': 'url_to_the_image'}
{'item_id': 1, 'is_front': True, 'url': 'url_to_the_image'}
{'item_id': 1, 'is_front': True, 'url': 'url_to_the_image'}
{'item_id': 1, 'is_front': True, 'url': 'url_to_the_image'}
{'item_id': 1, 'is_front': True, 'url': 'url_to_the_image'}
]
front_pic = None
for pic in item_pics:
if pic["is_front"]:
front_pic = pic
break
else:
front_pic = item_pics[0]
context = {"item_pics": item_pics, "front_pic": front_pic}
return render(....)
然后,在模板中,除了直接使用front_pic
之外,您无需执行其他任何操作。
使用自定义过滤器(参见放置此代码的文档链接):
@register.filter
def get_front_pic(item_pics):
for pic in item_pics:
if pic["is_front"]:
return pic
return item_pics[0]
在您的模板中:
{% load front_pic from yourtaglib %}
{% with item_pics|get_front_pic as front_pic %}
<img src="{{ front_pic.url }}">
{% endwith %}