模板中的django shuffle [英] django shuffle in templates
本文介绍了模板中的django shuffle的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
作为Django中关键字云功能的一部分,我正在尝试输出字符串列表。是否有模板过滤器,可让您随机播放列表中的项目?我以为这很简单,但是我在官方文档中找不到任何适用的过滤器。
as part of a keyword cloud function in Django, I am trying to output a list of strings. Is there a filter for templates which allows you to shuffle items in a list? I thought this would be straightforward, but I can't find any applicable filters in the official docs.
推荐答案
# app/templatetags/shuffle.py
import random
from django import template
register = template.Library()
@register.filter
def shuffle(arg):
tmp = list(arg)[:]
random.shuffle(tmp)
return tmp
然后在您的模板中:
{% load shuffle %}
<ul>
{% for item in list|shuffle %}
<li>{{ item }}</li>
{% endfor %}
</ul>
这篇关于模板中的django shuffle的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文