在模板中调用第n个模型的图像

时间:2018-07-05 03:47:50

标签: django django-templates

我正在使用以下内容将5张头像和5张推荐书传递给模板:

context = {
    'headshots': headshots,
    'testimonials', testimonials,
}

爆头模型的每个实例都有一个图像场。

在模板中,我想使用forloop.counter来写每个图像:

{% for t in testimonials %}
   {{ t.body }}
    <img src="{{ headshots[forloop.counter].image }}">
{% endfor %}

我的语法似乎错误,并且标记中的代码抛出错误。关于我哪里出了问题有什么想法吗?

1 个答案:

答案 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 %}