shuffle templatetag

 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 2 years, 1 month ago
  2. split filter by Ciantic 6 years, 11 months ago
  3. Create a random integer in a template by bartTC 7 months, 3 weeks ago
  4. Template Tag for Random Selection of Any Line by drhoden 3 years, 8 months ago
  5. Random Quotes by ferretsrule 6 years, 10 months ago

Comments

(Forgotten your password?)