A dict template tag

 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
from django.template import Library, TemplateSyntaxError

@register.tag(name='dict')
def do_dict(parser, token):
    try:
        tag_name, varname, key = token.contents.split(None, 2)
    except ValueError:
        raise TemplateSyntaxError("'dict' node requires a dict and a key name.")
    nodelist = parser.parse(('enddict',))
    parser.delete_first_token()
    return DictNode(nodelist, varname, key)

class DictNode(Node):
    def __init__(self, nodelist, varname, key):
        self.nodelist = nodelist
        self.varname, self.key = varname, key
        
    def render(self, context):
        output = self.nodelist.render(context)
        # get the top level context
        dict = context.dicts[len(context.dicts)-1]
        if self.varname in dict:
            dict[self.varname][self.key] = output
        else:
            dict[self.varname] = {self.key:output}
        return ''

More like this

  1. YUI Loader as Django middleware by akaihola 6 years ago
  2. Unobtrusvie Foldable Admin Interface by whiteinge 6 years, 3 months ago
  3. Integrate Wymeditor with filebrowser plugin by jonasvp 5 years, 5 months ago
  4. AddThis Social Networking TemplateTag by yeago 5 years, 3 months ago
  5. Template tags to integrate with modconcat by matthanger 4 years, 9 months ago

Comments

crashrox (on February 4, 2010):

import statement should be:

from django.template import Library, TemplateSyntaxError, Node

#

(Forgotten your password?)