Private Context Decorator

 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: Group variables into list by Killarny 4 years, 2 months ago
  2. inclusion tag with template as variable by forgems 4 years, 3 months ago
  3. Decorating class-based views by lqc 1 year, 3 months ago
  4. Repeat blocks with new context / simple Jinja-like macro system by miracle2k 5 years, 10 months ago
  5. Readonly fields on Form/Modelform by Killarny 4 years, 2 months ago

Comments

(Forgotten your password?)