问题
I currently have an image in a Django template which I would like to choose randomly every time the page is loaded:
<!--<img src="{% static 'images/640px-Waaah.jpg' %}"/>-->
<img src="{% static 'images/Crying_Baby.jpg' %}"/>
I've found some custom filters on Github for this purpose (e.g. random_image), but it seems to me like this should be possible using the built-in tags, in particular, the random filter.
It would be something like
{% with ['images/640px-Waaah.jpg', 'images/Crying_Baby.jpg']|random as crying_baby %}
<img src="{% static crying_baby %}"/>
{% endwith %}
but I don't believe this is valid DTL syntax. Any idea how I would go about this?
(By the way, the page is Django's default 404.html and is not passed any context, so I would prefer to do it by passing a list of baby images to the context).
回答1:
As you say, Django doesn't let you define lists in the template.
You could use a string of comma separated values and write a custom tag my_random
which splits the string and selects one of the values:
{% with "image1.jpg,image2.jpg"|my_random as image%}
Or you could just write a split
tag and pass the result to the built in random
tag.
{% with "image1.jpg,image2.jpg"|split:","|random as image %}
回答2:
I would approach it by writing a tag that returns a random image from a selection:
import random
from django import template
from django.conf import settings
register = template.Library()
@register.simple_tag
def random_image():
choices = getattr(settings,
RANDOM_IMAGE_LIST,
['http://thecatapi.com/api/images/get?format=src&type=png'])
return random.choice(choices)
Advantages over doing it in the template are chiefly reuse and its easier to change the selection since you only have to do it in one place, rather than hunt for templates.
I enhanced it a bit to pull a list from a configuration variable in settings.py
, if not set it will use a "default" image.
来源:https://stackoverflow.com/questions/49458428/how-to-select-a-random-image-in-a-django-template