简体   繁体   中英

Django context processor to show images

How to can add caption to each image in my images_people list?

This context_processor can be improved in the level practices sense?

I want show random images in my webpage, then I made a context processor

Context:

(previously added in my context_processors settings ...):

# -*- 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)}

In my template I am invoking this 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>

You could change the list in your context processor to be a list of 2-tuples of (url, caption).

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)}

Then in your template, {{ images.0 }} will be the URL, and {{ images.1 }} will be the caption.

If you don't like accessing the tuple by index, you could look at NamedTuple or create a class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM