Login

custom template tag sample

Author:
shinyzhu
Posted:
February 10, 2010
Language:
Python
Version:
1.1
Score:
-2 (after 2 ratings)

usage: <div class="content_box" id="tests" style="background:#cfc"> {% load extra %}

<p>{% get_current_time '%Y-%m-%d %I:%M %p' as the_current_time %}/{{ the_current_time }}</p>

{% upper %} <p>this is a test.</p> {% endupper %}

<p>{% a_current_time '%Y-%m-%d %I:%M %p' %}</p>

{% post_for_member member %}

</div>

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

Comments

Please login first before commenting.