1. Curtis Maloney
  2. django-sniplates

Source

django-sniplates / sniplates / templatetags / reuse.py


from django import template

register = template.Library()

class ReuseNode(template.Node):
    def __init__(self, blockname, extra_context):
        self.block = block
        self.extra_context = extra_context or {}

    def render(self, context):
        # Resolve out extra context
        extra_context = dict(
            (key, val.resolve(context)
            for key, val in self.extra_context.items()
        )
        context.update(extra_context)
        output = block.render(context)
        context.pop()
        return output

@register.tag
def reuse(parser, token):
    '''
    Re-use a previously defined block tag.
    '''
    bits = token.split_contents()
    if len(bits) < 2:
        raise TemplateSyntaxError("'%s' takes at least one argument." % bits[0])
    block_name = parser.compile_filter(bits[1])
    if not block_name in parser.__loaded_blocks:
        raise TemplateSyntaxError("Block '%s' is not defined." % block_name)
    block = parser.__loaded_blocks[block_name]
    if len(bits) > 2:
        extra_context = token_kwargs(bits[2:], parser)
    else:
        extra_context = {}
    return ReuseNode(block, extra_context)