Login

Sometimes Tag

Author:
deadwisdom
Posted:
June 1, 2009
Language:
Python
Version:
1.0
Tags:
tag random
Score:
2 (after 2 ratings)

Adds a templatetag that works like an if block, but . The one and only argument is a float that reflects the percentage chance. It defaults to .2, %20.

{% sometimes %} <img src='spy_behind_sniper.jpg'/> {% else %} <img src='sniper.jpg'/> {% endsometimes %}

-- or --

{% sometimes .001 %} You win! {% else %} Sorry, not a winner. Play again! {% endsometimes %}

-- or --

{% sometimes .5 %} This shows up half the time. {% endsometimes %}

 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. Reshape list for table, flatten index in nested loops by aquagnu 7 years, 5 months ago
  2. [UPDATE]Filter to resize a ImageField on demand by rafacdb 6 years, 11 months ago
  3. favicon Template Tag by benjy_mouse 5 years, 5 months ago
  4. load m2m fields objects by dirol 5 years, 1 month ago
  5. Template Tag of Django Image Thumb Creator by ayang23 4 years, 5 months ago

Comments

Please login first before commenting.