Django's standard inclusion_tag doesn't include context variables by default.
When you add takes_context you are required to manually merge the context
variables into the dict which your tag returns, which tends to result in
wasteful code or [possibly accidentally] leaking variables into the global
context (context.update({…})).
This decorator allows your inclusion tag to remain simple and still have safe
access to the global context for things like MEDIA_URL:
@register.inclusion_tag('my_template')
@private_context
def my_tag(context, …):
  return {"foo": 1, "bar": 2}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22  | from django.template.context import Context
def private_context(f):
    """
    Simple decorator which avoids the need to a) copy-and-paste code to force
    context variables into inclusion_tag templates and b) carefully avoid
    inclusion tag variables conflicting with global variables.
    
    Instead each inclusion tag will be called with a *copy* of the provided
    context variable and its results will be merged in to avoid leaking into
    the global context
    """
    from functools import wraps
    
    @wraps(f)
    def private_context_wrapper(context, *args, **kwargs):
        c = Context(context)
        rc = f(c, *args, **kwargs)
        c.update(rc)
        return c
    return private_context_wrapper
 | 
More like this
- Add Toggle Switch Widget to Django Forms by OgliariNatan 1 month, 4 weeks ago
 - get_object_or_none by azwdevops 5 months, 2 weeks ago
 - Mask sensitive data from logger by agusmakmun 7 months, 2 weeks ago
 - Template tag - list punctuation for a list of items by shapiromatron 1 year, 9 months ago
 - JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 1 year, 9 months ago
 
Comments
Please login first before commenting.