Dimitur Dimitrov
Dimitur Dimitrov

Reputation: 51

What is the right way to load different js file for each template in Django?

I want to load different .js, .css files (static files) for each template, but also to load same group of files for each of them.

Example:

first.html - Here I want to load jquery.js, jquery.css, maps.js

second.html - Here I want to load jquery.js, jquery.css without maps.js

third.html - Here I want to load test.js, maps.js

Right now I add all files in footer.html (.js files), or header.html (.css files) and include all of them, via {% include 'footer.html' %}

Upvotes: 1

Views: 1895

Answers (1)

dirkgroten
dirkgroten

Reputation: 20702

Your files should all extend a base.html file:

{% extend base.html %}

Then in base.html, add all the common scripts and css. Those will be inherited by all the templates. Also add an empty block page_scripts that you then fill in your various templates:

<head>
  <link rel="stylesheet" href="{% static 'jquery.css' %}" />
</head>
<body>
  {% block content %}
  {% endblock %}
  <footer>
    <script src="{% static 'jquery.js' %}"></script>
    {% block page_scripts %}{# Specific template scripts here #}{% endblock %}
  </footer>
</body>

Finally in your child templates, e.g. first.html:

{% block page_scripts %}
  <script src="{% static 'maps.js' %}"></script>
{% endblock %}

In this example, jquery.css and jquery.js are common for all templates. And maps.js is only loaded in your first.html page.

Upvotes: 4

Related Questions