Move all Javascript to a separate file in Django

I am starting with Django and am doing some stuff. I want the html files to be clean, no blocks <script>

. Is it possible even if my js part is using blocks {% url %}

?

Example:

page.html

<div> 
<h1> My home url is: </h1>
<div id="js-tag" ></div>
</div>
<script>
$(function(){
  $('#js-tag').html("{% url 'home' %}")
});
</script>

      

I want to remove this and put it in a separate js file and just import it into page.html

+3


source to share


2 answers


(Almost) anything is possible with Django!;)

You just need to put your JavaScript code in a separate HTML file and then just include it in your main template (here :) page.html

like this:



{% include 'path/to/my/template_file/js_code.html' %}

      

+3


source


You might want to use django-js-reverse to use named URL patterns in js files. You can also use the staticfiles app to manage your static assets in Django.

This will allow you to include your js files like this:

{% load static %}  {# Only load static once at the top of your file #}
<script src="{% static 'path/to/js/in/staticfiles.js' %}"></script>

      



And in the js file, you can use:

$('#js-tag').html(Urls.home());

      

+1


source







All Articles