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
- get_object_or_none by azwdevops 3 months, 2 weeks ago
- Mask sensitive data from logger by agusmakmun 5 months, 1 week ago
- Template tag - list punctuation for a list of items by shapiromatron 1 year, 7 months ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 1 year, 7 months ago
- Serializer factory with Django Rest Framework by julio 2 years, 2 months ago
Comments
Please login first before commenting.