Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django shuffle in templates

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.

like image 983
Darwin Tech Avatar asked Aug 23 '11 14:08

Darwin Tech


1 Answers

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>
like image 131
christophe31 Avatar answered Oct 07 '22 00:10

christophe31