Sometimes Tag

 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
import random
from django.template.defaulttags import register, Node, NodeList
class Sometimes(Node):
    def __init__(self, parser, token):
        args = token.contents.split()
        if len(args) == 1:
            self.weight = .2
        elif len(args) == 2:
            self.weight = float(args[1])
        else:
            raise TemplateSyntaxError("Invalid arguments to 'sometimes': %s" % args) 
        self.options = NodeList()
        while True:
            option = parser.parse( ('else', 'endsometimes') )
            token = parser.next_token()
            self.options.append(option)
            if token.contents == 'else':
 	            continue
            else:
 	            parser.delete_first_token()
 	            break
    
    def render(self, context):
        if random.random() <= self.weight:
            return self.options[0].render(context)
        else:
            return self.options[1].render(context)
            
register.tag("sometimes", Sometimes)

More like this

  1. Filter to resize a ImageField on demand by michelts 6 years, 1 month ago
  2. Cacheable resources by jbrisbin 4 years, 9 months ago
  3. [UPDATE]Filter to resize a ImageField on demand by rafacdb 4 years, 9 months ago
  4. Reshape list for table, flatten index in nested loops by aquagnu 5 years, 3 months ago
  5. Template Tag of Django Image Thumb Creator by ayang23 2 years, 3 months ago

Comments

(Forgotten your password?)