Created
January 17, 2017 02:59
-
-
Save mgd020/58b2495d654d5b8c7088ef2d42540af4 to your computer and use it in GitHub Desktop.
Render the content of a block somewhere else in a template
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from __future__ import absolute_import, division, print_function, unicode_literals | |
from django import template | |
from django.template.loader_tags import BlockNode, ExtendsNode | |
register = template.Library() | |
@register.simple_tag(takes_context=True) | |
def render_block(context, block_name): | |
t = context.template | |
while True: | |
for block in t.nodelist.get_nodes_by_type(BlockNode): | |
if block.name == block_name: | |
return block.render(context) | |
try: | |
extends = t.nodelist[0] | |
except IndexError: | |
return '' | |
extends.context_key += '_block_content' | |
try: | |
t = extends.get_parent(context) | |
except (AttributeError, template.TemplateDoesNotExist): | |
return '' | |
finally: | |
extends.context_key = ExtendsNode.context_key |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment