Created
September 30, 2013 15:01
-
-
Save augustomen/6765090 to your computer and use it in GitHub Desktop.
get_template_block() - returns a part of 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 django.template import loader, loader_tags | |
def get_template_block(template_name, block_name): | |
"""Searchs a returns a single block inside a template. | |
Useful for ajax reloading inside a template. | |
- template_name can be a filename or a list of filenames. | |
- block_name is the name of the block to look for: | |
{% block block_name %} | |
This function returns a BlockNode instance, which can be rendered to | |
a response, such as: | |
HttpResponse(block.render(context)) """ | |
template = loader.get_template(template_name) | |
return get_nodelist_block(template.nodelist, block_name) | |
def get_nodelist_block(nodelist, block_name): | |
"""Recursively searches the node tree to find a block named `block_name`""" | |
for node in nodelist: | |
if isinstance(node, loader_tags.BlockNode) and node.name == block_name: | |
return node | |
if node.child_nodelists: | |
for attr in node.child_nodelists: | |
child_nodelist = getattr(node, attr, None) | |
if child_nodelist: | |
block = get_nodelist_block(child_nodelist, block_name) | |
if block: | |
return block |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment