Skip to content

Instantly share code, notes, and snippets.

@mgd020 mgd020/
Created Feb 21, 2019

What would you like to do?
Add `set` like twigs to django templates
from django import template
from django.template.base import token_kwargs
register = template.Library()
class SetBlockNode(template.Node):
def __init__(self, name, nodelist): = name
self.nodelist = nodelist
def render(self, context):
context[] = self.nodelist.render(context)
return ""
class SetValuesNode(template.Node):
def __init__(self, extra_context):
self.extra_context = extra_context
def render(self, context):
for name, value in self.extra_context.items():
context[name] = value.resolve(context)
return ""
def do_set(parser, token):
"""Like `with`, but assigns to context immediately.
Also supports capturing block content.
bits = token.split_contents()[1:]
if not bits:
raise template.TemplateSyntaxError("'set' tag requires at least one argument.")
extra_context = token_kwargs(bits, parser)
if not extra_context:
if len(bits) != 1:
raise template.TemplateSyntaxError("'set' tag requires exactly one argument when used to capture block content.")
nodelist = parser.parse(('endset',))
return SetBlockNode(bits[0], nodelist)
return SetValuesNode(extra_context)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.