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 shuff开发者_开发技巧le items in a list? I thought this would be straightforward, but I can't find any applicable filters in the official docs.
it's straightforward to make yours.
# 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
and then in your template:
{% load shuffle %}
<ul>
{% for item in list|shuffle %}
<li>{{ item }}</li>
{% endfor %}
</ul>
Just to add, if it's a query set, it'll throw an error since object list can't be assigned. Here is a fix fr christophe31 code:
import random
from django import template
register = template.Library()
@register.filter
def shuffle(arg):
return random.shuffle([i for i in arg[:]])
'QuerySet' object does not support item assignment
精彩评论