如何在Django模板中选择随机图像? [英] How to select a random image in a Django template?

查看:121
本文介绍了如何在Django模板中选择随机图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前在Django模板中有一张图片,每次加载页面时我都希望随机选择:

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' %}"/>

我为此目的在Github上找到了一些自定义过滤器(例如 random_image ),但在我看来,使用内置标签(特别是 random 过滤器。

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.

就像是

{% with ['images/640px-Waaah.jpg', 'images/Crying_Baby.jpg']|random as crying_baby %}
  <img src="{% static crying_baby %}"/>
{% endwith %}

但我认为这不是有效的DTL语法。知道我会怎么做吗?

but I don't believe this is valid DTL syntax. Any idea how I would go about this?

(顺便说一下,该页面是Django的默认 404.html 且未传递任何上下文,因此,我宁愿通过将婴儿图片列表传递到上下文来完成此操作。)

(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).

推荐答案

正如您所说,Django不会

As you say, Django doesn't let you define lists in the template.

您可以使用逗号分隔的字符串值并编写自定义标签 my_random 会分割字符串并选择值之一:

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

或者您也可以编写分割标记并将结果传递到内置的 random 标记。

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

这篇关于如何在Django模板中选择随机图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆