Rendering JSON objects using a Django template after an Ajax call

前端 未结 8 1746
南笙
南笙 2020-12-02 03:59

I\'ve been trying to understand what\'s the optimal way to do Ajax in Django. By reading stuff here and there I gathered that the common process is:

  1. formul

相关标签:
8条回答
  • 2020-12-02 04:18

    There's no reason you can't return a rendered bit of HTML using Ajax, and insert that into the existing page at the point you want. Obviously you can use Django's templates to render this HTML, if you want.

    0 讨论(0)
  • 2020-12-02 04:20

    Templates are for the purpose of presentation. Responding with data in format X (JSON, JSONP, XML, YAML, *ml, etc.) is not presentation, so you don't need templates. Just serialize your data into format X and return it in an HttpResponse.

    0 讨论(0)
  • 2020-12-02 04:21

    Hey thanks vikingosegundo!

    I like using decorators too :-). But in the meanwhile I've been following the approach suggested by the snippet I was mentioning above. Only thing, use instead the snippet n. 942 cause it's an improved version of the original one. Here's how it works:

    Imagine you have a template (e.g., 'subtemplate.html') of whatever size that contains a useful block you can reuse:

         ........
        <div id="results">          
            {% block results %}
                {% for el in items %}
                       <li>{{el|capfirst}}</li>
                {% endfor %}
            {% endblock %}      
        </div><br />
         ........
    

    By importing in your view file the snippet above you can easily reference to any block in your templates. A cool feature is that the inheritance relations among templates are taken into consideration, so if you reference to a block that includes another block and so on, everything should work just fine. So, the ajax-view looks like this:

    from django.template import loader
    # downloaded from djangosnippets.com[942]
    from my_project.snippets.template import render_block_to_string
    
    def ajax_view(request):
        # some random context
        context = Context({'items': range(100)})
        # passing the template_name + block_name + context
        return_str = render_block_to_string('standard/subtemplate.html', 'results', context)
        return HttpResponse(return_str)
    
    0 讨论(0)
  • 2020-12-02 04:25

    When you are doing Ajax I don't think you have any use for templates. Template is there so that you can generate dynamic HTML on the server side easily and hence it provides few programming hooks inside HTML.

    In case of Ajax you are passing JSON data and you can format it as you want in Python. and HTML/document elements will be generated on client side using the JSON by some JavaScript library e.g. jQuery on client side.

    Maybe if you have a very specific case of replacing some inner HTML from server side HTML then maybe you can use templates but in that case why you would need JSON? You can just query the HTML page via Ajax and change inner or outer or whatever HTML.

    0 讨论(0)
  • 2020-12-02 04:29

    Unfortunately, Django templates are designed to be executed server side only. There is at least one project to render Django templates using Javascript, but I haven't used it and so I don't know how fast, well supported or up to date it is. Other than this, you have to either use the Django templates on the server or generate dynamic elements on the client without using templates.

    0 讨论(0)
  • 2020-12-02 04:35

    While templates are indeed just for presentation purposes, it shouldn't matter if you are doing it on the serverside or client side. It all comes down to separating the control logic that is performing an action, from the view logic that is just responsible for creating the markup. If your javascript control logic is having to handle how you are rendering or displaying the HTML, then you might be doing it wrong, but if you isolate that rendering logic to another object or function, and just passing it the data necessary for the render, then you should be fine; it mirrors how we separate our controllers, models and views on the server side.

    Take a look at the github project: http://github.com/comolongo/Yz-Javascript-Django-Template-Compiler

    It compiles django templates into optimized javascript functions that will generate your presentation html with data that you pass it. The compiled functions are in pure javascript, so there are no dependencies on other libraries. Since the templates are compiled instead of being parsed at runtime, the strings and variables are all already placed into javascript strings that just need to be concatenated, so you get a huge speed increase compared to techniques that require you to do dom manipulation or script parsing to get the final presentation. Right now only the basic tags and filters are there, but should be enough for most things, and more tags will be added as people start making requests for them or start contributing to the project.

    0 讨论(0)
提交回复
热议问题