Login

Partial JSON template rendering

Author:
barbuza
Posted:
October 28, 2007
Language:
Python
Version:
.96
Tags:
ajax
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. Class-Based AJAX fallback view by fahhem 4 years, 1 month ago
  2. jsonify template filter by skam 7 years, 10 months ago
  3. Publishing service endpoint uri to javascript by dberansky 4 years, 8 months ago
  4. FieldsetForm by Ciantic 7 years, 10 months ago
  5. escapejs block tag by baumer1122 7 years ago

Comments

Please login first before commenting.