Login

Private Context Decorator

Author:
acdha
Posted:
August 16, 2009
Language:
Python
Version:
1.1
Score:
1 (after 1 ratings)

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

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

Please login first before commenting.