I’m late too, but maybe we could add an inclusion_block_tag
. I’m not an expert but this is what I have (based on the simple_block_tag):
from functools import wraps
from inspect import getfullargspec, unwrap
from django.template import Library
from django.template.exceptions import TemplateSyntaxError
from django.template.library import InclusionNode, parse_bits
class ExtendedLibrary(Library):
def inclusion_block_tag(self, filename, func=None, takes_context=None, name=None):
def dec(func):
(
params,
varargs,
varkw,
defaults,
kwonly,
kwonly_defaults,
_,
) = getfullargspec(unwrap(func))
function_name = name or func.__name__
@wraps(func)
def compile_func(parser, token):
tag_params = params.copy()
if takes_context:
if len(tag_params) >= 2 and tag_params[1] == "content":
del tag_params[1]
else:
raise TemplateSyntaxError(
f"{function_name!r} is decorated with takes_context=True so"
" it must have a first argument of 'context' and a second "
"argument of 'content'"
)
elif tag_params and tag_params[0] == "content":
del tag_params[0]
else:
raise TemplateSyntaxError(f"'{function_name}' must have a first argument of 'content'")
bits = token.split_contents()[1:]
nodelist = parser.parse((f"end{function_name}", f"end_{function_name}"))
parser.delete_first_token()
args, kwargs = parse_bits(
parser,
bits,
tag_params,
varargs,
varkw,
defaults,
kwonly,
kwonly_defaults,
takes_context,
function_name,
)
return InclusionBlockNode(filename, nodelist, func, takes_context, args, kwargs)
self.tag(function_name, compile_func)
return func
return dec
class InclusionBlockNode(InclusionNode):
def __init__(self, filename, nodelist, *args, **kwargs):
super().__init__(filename=filename, *args, **kwargs)
self.nodelist = nodelist
def get_resolved_arguments(self, context):
resolved_args, resolved_kwargs = super().get_resolved_arguments(context)
# Restore the "content" argument.
# It will move depending on whether takes_context was passed.
resolved_args.insert(1 if self.takes_context else 0, self.nodelist.render(context))
return resolved_args, resolved_kwargs
Edit: formatting