我正在使用以下内容将5张头像和5张推荐书传递给模板:
context = {
'headshots': headshots,
'testimonials', testimonials,
}
爆头模型的每个实例都有一个图像场。
在模板中,我想使用forloop.counter
来写每个图像:
{% for t in testimonials %}
{{ t.body }}
<img src="{{ headshots[forloop.counter].image }}">
{% endfor %}
我的语法似乎错误,并且标记中的代码抛出错误。关于我哪里出了问题有什么想法吗?
答案 0 :(得分:1)
Django不允许在模板中进行间接变量查找,可能是因为它鼓励在模板中“编写代码”。更清洁的方法是在您的视图中zip
您的列表:
context = {
'testimonials_with_headshots': zip(testimonials, headshots),
...
}
然后
{% for testimonial, headshot in testimonials_with_headshots %}
{{ testimonial.body }}
<img src="{{ headshot.image.url }}">
{% endfor %}