Pig
Pig

Reputation: 2122

Django: How to load a script for every page?

Say I want to include bootstrap or angular for every single page in my views, is there a more elegant way than copying the same line to each file?

Upvotes: 0

Views: 1736

Answers (1)

Shang Wang
Shang Wang

Reputation: 25559

You need django template inheritance. Do the include in template base.html, and in there you define block that will be filled in for children templates:

<html>
    <!-- base.html -->
    ......
    {% block content %}
    {% endblock %}
    <!-- You include your js/css here -->
    <script type="text/javascipt" src="{{ STATIC_URL }}jquery.js">
    <link rel="stylesheet" type="text/css" href="mystyle.css">
</html>

then for all templates you extend base.html and override block content like so:

<!-- sub.html -->
{% extends "base.html" %}
{% block content %}
        <!-- You current page html goes here -->
{% endblock %}

In this way, what you have included in base.html will be automatically inherited and available in sub.html.

Upvotes: 2

Related Questions