Skip to content

Instantly share code, notes, and snippets.

@mgd020 mgd020/set_tags.py
Created Feb 21, 2019

Embed
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):
self.name = name
self.nodelist = nodelist
def render(self, context):
context[self.name] = 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 ""
@register.tag("set")
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',))
parser.delete_first_token()
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.