Login

django_template decorator

Author:
fredd4
Posted:
February 13, 2008
Language:
Python
Version:
.96
Score:
3 (after 3 ratings)

Easy way to caching template.

Very simple usage:

  @django_template("my_site.html")
  def master_home(request):
      variables = { 'title' : "Hello World!" }
      return variables
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# Author:  Shwagroo Team
# Website: (http://django-gems.blogspot.com/)

from django.template import loader, RequestContext
from django.http import HttpResponse, Http404

from settings import DEBUG

decorator_with_args = lambda decorator: lambda *args, **kwargs: lambda func: decorator(func, *args, **kwargs )

templates = {}


def django_template_to_string( request, variables, template ):
    """
      usage:
      
      django_template_to_string( request, { 'title' : 'hello' }, "base.html" )
    """
    if not DEBUG:
        temp = templates.get( template )
        if temp is None:
            temp = loader.get_template(template)
            templates[template] = temp
        
    else:
        temp = loader.get_template(template)

    c = RequestContext(request)
    c.update(variables)
    return temp.render(c)

@decorator_with_args
def django_template(func, template=None):
    """
      usage:

      @django_template("moja_strona.html")
      def master_home(request):
          variables = { 'title' : "Hello World!" }
          return variables
    """
    def wrapper(request,*args,**kwargs):
        variables = func(request, *args, **kwargs )
        
        string = django_template_to_string( request, variables, template )

        return HttpResponse( string )
        
    wrapper.__name__ = func.__name__
    wrapper.__dict__ = func.__dict__
    wrapper.__doc__ = func.__doc__
    return wrapper

More like this

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

Comments

Please login first before commenting.