Django custom tags and filters

3 examples of django custom tags and filters.

 1 from django.template import Node, Library, resolve_variable
 2 
 3 # Tag that set a context variable.
 4 # Example uses are in setvar function. It's kinda stupid/dirty function
 5 # for assigning lists as well. It should probably be 2 different tags.
 6 # But it's easy to do from here.
 7 class SetVar(Node):
 8   def __init__(self, variable, value, valueIsVariable=False):
 9     self.valueIsVariable = valueIsVariable
10     self.variable = variable
11     self.value = value
12 
13   def render(self, context):
14     if self.valueIsVariable:
15       context.dicts[-1][self.variable] = \
16           resolve_variable(self.value, context)
17     else:
18       context.dicts[-1][self.variable] = self.value
19     return ''
20 
21 def setvar(parser, token):
22   bits = token.split_contents()
23   # first case: {{ "{% setvar myVar as otherVar "}}%}
24   if len(bits) == 4 and bits[2] == "as":
25     return SetVar(bits[1], bits[3], True)
26   # second case: {{ "{% setvar myVar abcd "}}%}
27   # myVar = "abcd"
28   if len(bits) == 3:
29     return SetVar(bits[1], bits[2])
30   # {{ "{% setvar myVar "}}%}
31   # myVar = None
32   elif len(bits) == 2:
33     return SetVar(bits[1], None)
34   # {{ "{% setvar myVar a b c d e f "}}%}
35   # myVar = ['a', 'b', 'c', 'd', 'e', 'f']
36   return SetVar(bits[1], bits[2:])
37 
38 #==========================
39 # Filter jsid. Very simple replace to make a basic domain
40 # name a valid javascript ID.
41 
42 def jsid(value):
43   return 'z_' + value.replace('.', '_').replace('-', '__')
44 
45 #==========================
46 # Tag that split a string using a separator, and put the result
47 # in a context variable.
48 # {{ "{% split myVar "," otherVar "}}%}
49 # if myVar is "a,b,c,d", then otherVar = ['a', 'b', 'c', 'd']
50 
51 class SplitStringOn(Node):
52   def __init__(self, string, spliton, result):
53     self.string = string
54     self.spliton = spliton
55     self.result = result
56 
57   def render(self, context):
58     txt = resolve_variable(self.string, context)
59     context[self.result] = txt.split(self.spliton)
60     return ''
61 
62 def split(parser, token):
63   bits = token.split_contents()
64   if len(bits) == 4:
65     # the second argument (bits[2]) will be something like "asd" - including the ".
66     # So we remove them.
67     return SplitStringOn(bits[1], bits[2][1:-1], bits[3])
68   raise TemplateSyntaxError, "split tag takes exactly 3 arguments"
Reading data from a Wintech Alti bike computer under linux » « Django template standalone