Sebastian Auberger
Sebastian Auberger

Reputation: 480

Render JSON objects through Django template-tag

I receive a dictionary of Django objects in a JSON format via AJAX in the template. Is there any possibility to render this dictionary through a Django template-tag? Can I call a Django template-tag from jQuery and transfer the object as a parameter to it?

The current solution is to tediously construct the html in jQuery:

$.ajax({
    url: url,
    type: "POST",
    success: function(data) {
        var obj = $.parseJSON(data);
        $.each(obj, function() {
            data = this['fields'];

            post += "<p id='" + this['pk'] + "'>" + data['creator'] + data['created'] + data['body'];
            post += "depth: " + data['depth'];
            post += "<a name='" + this['pk'] + "' class='show_answers' href='" + show_url + "'>Show</a>";
            post += "<a name='" + this['pk'] + "' href='" + answer_url + "'>Answer</a></p>";
            post += "<div id='" + this['pk'] + "_div'></div>";
        });
        $('#' + div_id).html(post);
    },
    crossDomain: false
}); 

Upvotes: 0

Views: 1247

Answers (1)

bruno desthuilliers
bruno desthuilliers

Reputation: 77932

Templatetags are server-side, so no, you cannot use django's templating to handle the result of an Ajax request - not directly at least. Possible solutions :

  • you can eventually write a view that would take your json data and returns formatted html, but that's going to be a bit on the heavy side.

  • if the json comes from your own application, you could return an html fragment instead of json.

  • if the json comes from another site, you could also have a view in your app doing the request and returning a formatted html fragment from the json (then you'd post to this view).

  • finally if you're app is heavy on ajax/json stuff, you may want to use some js templating framework or something like angular.js

Upvotes: 1

Related Questions