Alex Rivera | Logout

Django: How can I get a block from a template?

Asked 2010-04-21T23:09:46.397
10

Suppose my template has in it something like {% block subject %}my subject{% endblock %} and I load this template with tmpl = loader.get_template('mytemplate.html'), how can I extract "my subject"?

Edit
Report

1 Answer

3

I wanted this to make an include tag that gets only a section of the template in question. I'm sharing it here just in case someone else wanted it for the same reason.

Usage: {% include_block "template.html" "block_name" %}

@register.tag
def include_block(parser, token):
    try:
        tag_name, include_file, block_name = token.split_contents()
    except ValueError:
        raise template.TemplateSyntaxError("%r tag requires a two arguments" % (token.contents.split()[0]))

    #pass vars with stripped quotes 
    return IncludeBlockNode(include_file.replace('"', ''), block_name.replace('"', ''))

class IncludeBlockNode(template.Node):
    def __init__(self, include_file, block_name):
        self.include_file = include_file
        self.block_name = block_name

    def _get_node(self, template, context, name):
        '''
        taken originally from
        http://stackoverflow.com/questions/2687173/django-how-can-i-get-a-block-from-a-template
        '''
        for node in template:
            if isinstance(node, BlockNode) and node.name == name:
                return node.nodelist.render(context)
            elif isinstance(node, ExtendsNode):
                return self._get_node(node.nodelist, context, name)

        raise Exception("Node '%s' could not be found in template." % name)

    def render(self, context):
        t = get_template(self.include_file)
        return self._get_node(t, context, self.block_name)
answered 2011-12-09T20:30:43.767

Your Answer