Login

Partial JSON template rendering

Author:
barbuza
Posted:
October 28, 2007
Language:
Python
Version:
.96
Score:
-1 (after 3 ratings)

this decorator will render template and encode it as JSON string if it find ajax_request variable in GET. It will not parse parent (extended) templates, only given template and nested (included). Only blocks will be rendered and encoded to JSON naming blockBLOCKNAME. Simple javascript can do ajax request adding ?ajax_request or &ajax_request (if needed) and update given html elements if they id's are same as blockBLOCKNAME. you can find a full code (including javascript) at my (http://projects.barbuza.info/trac/browser/django_addons/django_ajax/trunk/ sandbox).

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
from django.http import HttpResponse
from django.template import RequestContext, loader
from django.template.loader_tags import BlockNode
from simplejson import dumps

def ajax_render_to(template_name):
    def deco_wrap(func):
        def wrap(request, *args, **kwargs):
            res = func(request, *args, **kwargs)
            if type(res) is not dict:
                return res
            template = loader.get_template(template_name)
            cont = RequestContext(request, res)
            if not 'ajax_request' in request.GET:
                return HttpResponse(template.render(cont))
            blocks = []
            for node in template.nodelist:
                blocks = blocks + node.get_nodes_by_type(BlockNode)
            result = {}
            for block in blocks:
                result["block__%s"%block.name] = block.render(cont)
            return HttpResponse(dumps(result))
        return wrap
    return deco_wrap

More like this

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

Comments

Please login first before commenting.