Login

Sometimes Tag

Author:
deadwisdom
Posted:
June 1, 2009
Language:
Python
Version:
1.0
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. Template tag - list punctuation for a list of items by shapiromatron 3 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 3 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 10 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 11 months ago
  5. Help text hyperlinks by sa2812 12 months ago

Comments

Please login first before commenting.