I am refactoring my Django templates to use components for better manageability and to reduce duplication. Specifically, I am using {% include %}
to include HTML and JavaScript code from partial templates.
Here’s how my templates are currently structured:
<!-- base.html -->
<head>...</head>
<body>
{% block content %}{% endblock %}
<script>
<!--- jQuery and other global JS dependencies --->
</script>
{% block script %}{% endblock %}
</body>
<!-- child.html -->
{% extends 'base.html' %}
{% block content %}
child 1
{% include 'partial.html' %}
...
{% endblock %}
{% block script %}
<script>// Script 1</script>
{% endblock %}
<!-- partial.html -->
<div>Partial content</div>
{% block script %}
<script>// Script 2</script>
{% endblock %}
Problem:
The output HTML renders as follows:
<head>...</head>
<body>
child 1
<div>Partial content</div>
<script>// Script 2</script>
<script><!--- jQuery and other global JS dependencies ---></script>
<script>// Script 1</script>
</body>
In this structure, Script 2
is executed before the jQuery and other global dependencies defined in base.html
, causing issues.
How can I ensure that JavaScript defined in partials is included after the global scripts in the base template, even when using {% include %}
?