Created
September 25, 2025 08:10
-
-
Save danjac/7c25d300528651314bce942ee5ac2000 to your computer and use it in GitHub Desktop.
Very simple Django block include tag using @simple_block_tag
This file contains hidden or 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
@register.simple_block_tag(takes_context=True) | |
def blockinclude( | |
context: Context, | |
content: str, | |
template_name: str, | |
*, | |
only: bool = False, | |
**extra_context, | |
) -> str: | |
"""Renders include in block. | |
Example: | |
{% blockinclude "header.html" %} | |
title goes here | |
{% endblockinclude %} | |
header.html: | |
<h1>{{ content }}</h1> | |
If `only` is passed it will not include outer context. | |
""" | |
if not context.template: | |
raise template.TemplateSyntaxError( | |
"Can only be used inside a template context." | |
) | |
tmpl = context.template.engine.get_template(template_name) | |
context = context.new() if only else context | |
with context.push(content=content, **extra_context): | |
return tmpl.render(context) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment