PageRenderTime 17ms CodeModel.GetById 9ms app.highlight 6ms RepoModel.GetById 1ms app.codeStats 0ms

/blogmaker/util/templatetags/prefab_tags.py

http://blogmaker.googlecode.com/
Python | 81 lines | 67 code | 10 blank | 4 comment | 1 complexity | 7c50228e9449ddbfc472adf29d5c228e MD5 | raw file
 1''' @copyright:Copyright (c) 2006-2007, PreFab Software Inc. '''
 2
 3from django import template
 4from django.conf import settings
 5
 6from blogmaker.util import expand_shortcuts
 7
 8register = template.Library()
 9
10register.filter('expand_shortcuts', template.defaultfilters.stringfilter(expand_shortcuts))
11
12@register.simple_tag
13def setting(name):
14    return getattr(settings, name)
15    
16    
17@register.tag
18def getsetting(parser, token):
19    ''' Access a setting and assign a variable in the template
20        Usage: {% getsetting setting as var %}
21    '''
22    args = token.split_contents()
23    if len(args) != 4:
24        raise template.TemplateSyntaxError, "%r tag requires two or four arguments" % args[0]
25    
26    return GetSettingNode(args[1], args[3])
27
28class GetSettingNode(template.Node):
29    def __init__(self, setting, var):
30        self.setting = setting
31        self.var = var
32        
33    def render(self, context):
34        value = getattr(settings, self.setting)
35        context[self.var] = value
36        return ''
37        
38        
39@register.tag('with')
40def do_with(parser, token):
41    """
42    Add a value to the context (inside of this block) for easy access.
43
44    Example::
45
46        {% with person.addresses.all as addresses %}
47            {% if addresses %}
48                <h3>Addresses</h3>
49                {% for address in addresses %}
50                   ...
51                {% endfor %}
52            {% endif %}
53        {% endwith %}
54    
55    From http://www.djangosnippets.org/snippets/132/
56    """
57    bits = list(token.split_contents())
58    if len(bits) != 4 or bits[2] != "as":
59        raise template.TemplateSyntaxError, "%r expected format is 'value as name'" % token.contents[0]
60    var = parser.compile_filter(bits[1])
61    name = bits[3]
62    nodelist = parser.parse(('endwith',))
63    parser.delete_first_token()
64    return WithNode(var, name, nodelist)
65
66class WithNode(template.Node):
67    def __init__(self, var, name, nodelist):
68        self.var = var
69        self.name = name
70        self.nodelist = nodelist
71
72    def __repr__(self):
73        return "<WithNode>"
74
75    def render(self, context):
76        val = self.var.resolve(context)
77        context.push()
78        context[self.name] = val
79        output = self.nodelist.render(context)
80        context.pop()
81        return output