Login

shuffle templatetag

Author:
deanmalmgren
Posted:
February 25, 2011
Language:
Python
Version:
1.2
Tags:
template-tag iterable shuffle
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

  1. Template filter to get each attribute value in an iterable by strangefeatures 3 years, 2 months ago
  2. split filter by Ciantic 8 years ago
  3. Create a random integer in a template by bartTC 1 year, 9 months ago
  4. Template Tag for Random Selection of Any Line by drhoden 4 years, 10 months ago
  5. Random Quotes by ferretsrule 7 years, 11 months ago

Comments

Please login first before commenting.