Partial JSON template rendering

 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. Auto rendering decorator with options by Batiste 5 years, 4 months ago
  2. Class-Based AJAX fallback view by fahhem 2 years, 4 months ago
  3. Mobilize your Django site by stevena0 4 years, 2 months ago
  4. Encoding datetime for JSON consumers like YUI by acdha 3 years, 5 months ago
  5. Render specific blocks from templates (useful for AJAX) by sciyoshi 5 years ago

Comments

(Forgotten your password?)