Login

Private Context Decorator

Author:
acdha
Posted:
August 16, 2009
Language:
Python
Version:
1.1
Tags:
templatetag decorator context inclusion_tag
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. Enhancing template tags with "as variable" syntax by ctrochalakis 5 years, 10 months ago
  2. media_url context variable by marchino 8 years, 2 months ago
  3. A GET string modifier templatetag by cogat 6 years, 6 months ago
  4. CatchTag - Catching the content and saving it to a variable by limodou 8 years, 4 months ago
  5. testdata tag for templates by showell 6 years, 2 months ago

Comments

Please login first before commenting.