aboutsummaryrefslogtreecommitdiff
path: root/templatetags/withsetting.py
blob: 464cc78ae3a2a73499a287233b42aca1e63d73ac (plain)
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
# -*- coding: utf-8 -*-
# This file is part of GCIDE                                
# Copyright (C) 2012 Sergey Poznyakoff
#
# GCIDE is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3, or (at your option)
# any later version.
#
# GCIDE is distributed in the hope that it will be useful,      
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.   
#
# You should have received a copy of the GNU General Public License
# along with GCIDE.  If not, see <http://www.gnu.org/licenses/>.

from django import template
from django.template import Node, NodeList, Template, Context, Variable
from django.template import TemplateSyntaxError
from django.conf import settings
import re

register = template.Library()

class WithSettingNode(template.Node):
    def __init__(self, dict, nodelist):
        self.dict = dict
        self.nodelist = nodelist

    def __repr__(self):
        return "<WithSettingNode>"

    def render(self, context):
        context.push()
        context.update(self.dict)
        output = self.nodelist.render(context)
        context.pop()        
        return output


def mkdict(name,bits,dict):
    if len(bits) < 3 or bits[1] != "as":
        raise TemplateSyntaxError("%r expected format is 'value as name'" %
                                  name)
    if not bits[2].endswith(','):
        if len(bits) > 3:
            raise TemplateSyntaxError("%r expected format is 'value as name'" %
                                      name)
        dict[bits[2]] = eval('settings.' + bits[0])
    else:
        dict[bits[2][0:-1]] = eval('settings.' + bits[0])
        mkdict(name,bits[3:],dict)

#@register.tag
def do_withsetting(parser, token):
    bits = list(token.split_contents())
    dict = {}
    try:
        mkdict(bits[0], bits[1:], dict)
    except AttributeError, diag:
        raise TemplateSyntaxError("%r: %s " % (bits[0], diag))
    nodelist = parser.parse(('endwithsetting',))
    parser.delete_first_token()
    return WithSettingNode(dict, nodelist)

do_withsetting = register.tag('withsetting', do_withsetting)

Return to:

Send suggestions and report system problems to the System administrator.