- Author:
- deanmalmgren
- Posted:
- February 25, 2011
- Language:
- Python
- Version:
- 1.2
- Score:
- 0 (after 0 ratings)
This is useful for randomizing an iterable of objects in place in a django template. Usage:
{% load shuffle %}
{# now some_list is ordered #}
{% shuffle some_list %}
{# now some_list is randomized #}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | """used to shuffle a list in a template
"""
import random
from django import template
class ShuffleNode(template.Node):
"""node for shuffling iterable object in place in template"""
def __init__(self, iterable_var):
self.iterable_var = template.Variable(iterable_var)
def render(self, context):
# resolve the article object from the context
iterable_var = self.iterable_var.resolve(context)
# shuffle it
iterable_var = [x for x in iterable_var]
random.shuffle(iterable_var)
# save result in context and return
context[self.iterable_var] = iterable_var
return ''
register = template.Library()
@register.tag
def shuffle(parser, token):
"""shuffle a list within a template
{% shuffle iterable_object %}
"""
contents = token.split_contents()
if len(contents) == 2:
tag_name, iterable_var = contents
else:
msg = "%r tag requires 1 argument" % token.contents.split()[0]
raise template.TemplateSyntaxError, msg
return ShuffleNode(iterable_var)
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 1 week ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 5 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
Please login first before commenting.