1 | from django import template
|
---|
2 |
|
---|
3 | register = template.Library()
|
---|
4 |
|
---|
5 | class SetContextNode(template.Node):
|
---|
6 | """
|
---|
7 | This class defines renderer which just updates current template context with the rendered output of the block inside tags.
|
---|
8 | """
|
---|
9 | def __init__(self, nodelist, variable):
|
---|
10 | self.nodelist = nodelist
|
---|
11 | self.variable = variable
|
---|
12 |
|
---|
13 | def render(self, context):
|
---|
14 | context[self.variable] = self.nodelist.render(context)
|
---|
15 | return ''
|
---|
16 |
|
---|
17 | @register.tag
|
---|
18 | def setcontext(parser, token):
|
---|
19 | """
|
---|
20 | Sets (updates) current template context with the rendered output of the block inside tags.
|
---|
21 | """
|
---|
22 | nodelist = parser.parse(('endsetcontext',))
|
---|
23 | args = list(token.split_contents())
|
---|
24 |
|
---|
25 | if len(args) != 3 or args[1] != "as":
|
---|
26 | raise TemplateSyntaxError("%r expected format is 'as name'" % args[0])
|
---|
27 | variable = args[2]
|
---|
28 |
|
---|
29 | parser.delete_first_token()
|
---|
30 |
|
---|
31 | return SetContextNode(nodelist, variable)
|
---|