how to organize JS files in Django?

Django template engine has already provided a tag for inherit your HTML structure called 'extend'.

Tag "extends" is a using for extends a parent template.

{% extends "base.html" %} uses the literal value "base.html" as the name of the parent template to extend.

base.html is the parent template that can extendable.

{% load staticfiles %}
<html lang="en">
    <head><title>Hello World</title></head>
    <body>
        <div id="content">
            {% block content %}{% endblock %}
        </div>

        {% block scripts %}
        <script src="{% static 'js/main.js' %}"></script>
        {% endblock %}
 
    </body>
</html>

and you have another HTML called milk.html that you need everything same as the base.html but include milk.js you just do something like this.

{% load staticfiles %}
{% extends "base.html" %}

{% block scripts %}
    <!-- block.super will get the content of the block from the parent template -->
    {{ block.super }}
    <script src="{% static 'js/milk.js' %}"></script>
{% endblock %}

Read more about docs[1]: [1]: https://docs.djangoproject.com/en/dev/ref/templates/builtins/#std:templatetag-extends


Being lazy, and extending the admin templates with {% extends admin/base.html %} I found that using {% block scripts %} did not work. The JavaScript was not sent to the browser. However base.html has a built-in block {% block extrahead %} which is empty and just the ticket for inserting additional content like scripts into the header.

{% block extrahead %}
<script src="{{ STATIC_URL }}js/milk.js"></script>
{% endblock %}

In your base.html file, add a block inside the head tag like this:

{% block scripts %}

<!-- some default content here -->

{% endblock %}

Now in your different templates files:

{% block scripts %}

<!-- insert per template scripts here -->

{% endblock %} 

So in the templates with Milk, it would be like:

{% block scripts %}

<script src="{{ STATIC_URL }}js/milk.js"></script>

{% endblock %}