Skip to content

Instantly share code, notes, and snippets.

@vmihailenco
Created July 3, 2011 13:30
Show Gist options
  • Save vmihailenco/1062223 to your computer and use it in GitHub Desktop.
Save vmihailenco/1062223 to your computer and use it in GitHub Desktop.
Django set template tag
from django import template
register = template.Library()
class SetNode(template.Node):
def __init__(self, key, nodelist, return_result=False):
self.key = key
self.nodelist = nodelist
self.return_result = return_result
def render(self, context):
value = self.nodelist.render(context)
for d in context.dicts:
d[self.key] = value
if self.return_result:
return value
else:
return ''
@register.tag
def set(parser, token, return_result=False):
try:
tag_name, key = token.split_contents()
except ValueError:
raise template.TemplateSyntaxError(
'%r tag requires a single argument' %
token.contents.split()[0])
nodelist = parser.parse(('endset',))
parser.delete_first_token()
return SetNode(key, nodelist, return_result)
@register.tag
def setget(parser, token):
return set(parser, token, return_result=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment