Django上下文处理器显示图像

时间:2017-11-01 13:11:00

标签: django django-templates

如何为images_people列表中的每张图片添加标题?

这个context_processor可以在级别实践意义上进行改进吗?

我想在我的网页上显示随机图像,然后我制作了一个上下文处理器

上下文:

(之前在我的context_processors设置中添加...):

# -*- coding: utf-8 -*-

from random import choice

images_people = ['https://s3-sa-east-1.amazonaws.com/ihost-project/assets/img/bolivia2.jpg','2',
          'https://s3-sa-east-1.amazonaws.com/ihost-project/assets/img/bolivia3.jpg',
          'https://s3-sa-east-1.amazonaws.com/ihost-project/assets/img/bolivia4.jpg',
          'https://s3-sa-east-1.amazonaws.com/ihost-project/assets/img/bolivia-children.jpg',
          'https://s3-sa-east-1.amazonaws.com/ihost-project/assets/img/ElZocalo.jpg',
          'https://s3-sa-east-1.amazonaws.com/ihost-project/assets/img/israel.jpg',
          ]

def images(request):
    return {'images': choice(images_people)}

在我的模板中,我正在调用此context_processor:

<div class="portrait">
    <div class="img-cont" style="background: url('{{ images  }}') no-repeat center; background-size:cover;">
    </div>
         # Add caption to image
         <!-- <span></span> -->
</div>

1 个答案:

答案 0 :(得分:2)

您可以将上下文处理器中的列表更改为(元组,标题)的2元组列表。

images_people = [
    ('https://s3-sa-east-1.amazonaws.com/ihost-project/assets/img/bolivia2.jpg', 'Caption 1'), 
    ('https://s3-sa-east-1.amazonaws.com/ihost-project/assets/img/bolivia3.jpg', 'Caption 2),
    ...
]

def images(request):
    # n.b changed from `images` to `image` since it's a single image
    return {'image': choice(images_people)}

然后在您的模板中,{{ images.0 }}将成为网址,{{ images.1 }}将成为标题。

如果您不喜欢按索引访问元组,可以查看NamedTuple或创建一个类。