How to structure js block in template called with include?

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 %}?

1 Like

How do you want to implement HTML?

If it’s simply a problem with a single tag, you can just insert that tag into another template, but since you didn’t do that, I don’t think you’re explaining the problem properly.

And I don’t think it’s good for a block to exist in an included template.

1 Like

I’ve rewritten the question to better illustrate my problem. In short, is it possible to ensure any script tag I defined in partial to be appended in the script block in the base?

Simply put, no.

See the Note box at the end of the section of the docs for the include tag to understand the semantics of that tag relative to blocks.

As far as I know, the way you want is not possible.

It is recommended to separate script tags and use template include when necessary.