Skip to content

Instantly share code, notes, and snippets.

@mgd020
Created January 17, 2017 02:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mgd020/58b2495d654d5b8c7088ef2d42540af4 to your computer and use it in GitHub Desktop.
Save mgd020/58b2495d654d5b8c7088ef2d42540af4 to your computer and use it in GitHub Desktop.
Render the content of a block somewhere else in a template
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