dabadaba
dabadaba

Reputation: 9522

Django: load template after AJAX request

I am using Django templates and in a particular one, I am loading a couple of divs with content performing two AJAX requests to make things faster.

The main template I am talking includes a view at the end, which is actually mostly JS. The thing is this JS is dependent on the data loaded in those AJAX requests, so the scripts are being rendered by the template before the necessary data is in the HTML.

A quick scheme:

{# main template #}
{% block content %}
  <div id="main">...</div>
  <div id="load-data-1"></div>
  <div id="load-data-2"></div>
{% endblock %}

{% block js }%
  {% include 'template_with_scripts.html' %}
{% endblock %}

template_with_scripts.html

<script>
  $.get(url1, function(data) { $('#load-data-1').html(data); });
  $.get(url2, function(data) { $('#load-data-2').html(data); });
</script>

{% include 'scripts_related_with_ajax_loaded_data.html' %}

So what I need to do is to load the scripts after the AJAX requests are done, as explained in this answer.

But my question is how to go about loading that scripts_related_with_ajax_loaded_data.html file after the AJAX calls have finished. Should I make a new route and view to return the rendered context as HTML? Seems weird and a bit of an overkill. Is there a tag that just renders whatever template you pass, so I can append it to the HTML?

Upvotes: 1

Views: 1833

Answers (1)

One thing you should understand about Django templates is that they are rendered by your server, so no template tags will work on the client side. So yes, you should create a separate endpoint and retrieve data from it via Javascript.

Upvotes: 1

Related Questions