In some of the code I’m working on, the author max AJAX calls to a Django view that returns JSON.
Once the JSON is retrieved, it’ll be injected into the page with a function that looks like this (note, this is a simplification, but I’m sure you know what I’m getting at here):
function build_event_listing(events) {
var html = '';
for(int i = 0; i < events.length; i++) {
event = events[i];
html += "<h2>" + event.title + "</h2>\n";
html += "<p>" + event.description + "</p>";
html += "Click <a href='/event/view/" + event.id + "'>here<a> for more info.";
}
events_div.html(html);
}
I really don’t like this approach. To change the look of each event listing, the designer would have to modify that ugly JS. I’d much rather make use of Django’s templating system, but I’m wondering how I can do this?
I had the idea of writing the view like this:
def view_listings(req):
events = models.Event.objects.all()
html = []
for event in events:
html.append(
render_to_string('event/single_event.html', {
'event': event,
}, context_instance=RequestContext(req))
return HttpResponse(''.join(html), mimetype='text/html')
… but it just seems like there should be a better way.
Any ideas?
I wrote a Django/Ajax library that organises this for you. You write your template as such:
In your view you would do something like:
There is also a template tag that flags a single value for replacement, eg
{% adjax event.title %}and thenadjax.update(request, event, ('title', 'description', 'id'))
in the view. But this is only single objects currently, not query sets. It’s a good idea though, I might quickly implement it.See http://adjax.hardysoftware.com.au/how/