Login

django_template decorator

Author:
fredd4
Posted:
February 13, 2008
Language:
Python
Version:
.96
Tags:
template render decorator
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. Enhancing template tags with "as variable" syntax by ctrochalakis 5 years, 11 months ago
  2. Simple template tag to do |stringformat filter with format from a variable by leopd 4 years, 3 months ago
  3. Private Context Decorator by acdha 5 years, 11 months ago
  4. CatchTag - Catching the content and saving it to a variable by limodou 8 years, 5 months ago
  5. Render Decorator by dahool 5 years, 10 months ago

Comments

Please login first before commenting.