custom template tag sample

 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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
from django import template
from datetime import datetime
import re

from post.models import Post

register = template.Library()

@register.tag(name='get_current_time')
def do_current_time(parser,token):
    '''
    A custom tag need 2 steps:
    '''
    # This version uses a regular expression to parse tag contents
    try:
        # Splitting by None == splitting by spaces
        tag_name, arg = token.contents.split(None,1)
    except ValueError:
        msg = '%r tag requires arguments.' % token.contents[0]
        raise template.TemplateSyntaxError(msg)
        
    m = re.search(r'(.*?) as (\w+)',arg)
    
    if m:
        fmt,var_name = m.groups()
    else:
        msg = '%r tag had invalid arguments.' % tag_name
        raise template.TemplateSyntaxError(msg)
        
    if not (fmt[0] == fmt[-1] and fmt [0] in ('"',"'")):
        msg = "%r tag's argument should be in quotes." % tag_name
        raise template.TemplateSyntaxError(msg)
        
    return CurrentTimeNode(fmt[1:-1],var_name)
    
class CurrentTimeNode(template.Node):
    '''
    A custom tag Node.
    '''
    def __init__(self,format_string,var_name):
        self.format_string = str(format_string)
        self.var_name = var_name
        
    def render(self,context):
        now = datetime.now()
        
        context[self.var_name] = now.strftime(self.format_string)
        
        return ''
    
@register.tag(name='upper')
def do_upper(parser,token):
    nodelist = parser.parse(('endupper',))
    parser.delete_first_token()
    
    return UpperNode(nodelist)
    
class UpperNode(template.Node):
    def __init__(self,nodelist):
        self.nodelist = nodelist
        
    def render(self,context):
        output = self.nodelist.render(context)
        
        return output.upper()
        
@register.simple_tag
def a_current_time(format_string):
    '''
    Simple tag
    '''
    try:
        return datetime.now().strftime(str(format_string))
    except UnicodeEncodeError:
        return ''
        
@register.inclusion_tag('tags/inclusion.html')
def post_for_member(member):
    '''
    Inclusion tag sample
    '''
    post_list = Post.objects.filter(user__id=member.id)
    return {'post_list':post_list}

More like this

  1. Cookie based flash errors and notices (a la Rails) by alexk 4 years, 8 months ago
  2. "Zoom in" on rendered HTML that the test client returns by peterbe 4 years, 1 month ago
  3. Templatetag startswith + message tuned by io_error 4 years, 11 months ago
  4. Yet another SQL debugging facility by miracle2k 5 years, 9 months ago
  5. Generic CSV Export by zbyte64 4 years, 11 months ago

Comments

(Forgotten your password?)