0

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?

Pig
  • 2,002
  • 5
  • 26
  • 42
  • Possible duplicate of [Django project base template](http://stackoverflow.com/questions/14720464/django-project-base-template) – P3zhman Jan 16 '16 at 12:01

1 Answers1

2

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.

Shang Wang
  • 24,909
  • 20
  • 73
  • 94
  • Can the base.html be open-ended? For example can it end with the css link without the

    tag?

    – Pig Jan 17 '16 at 04:29
  • Well, template inheritance can happen among any two or more templates. As long as you feel like there's something in common for two templates and it would make sense to extract the common part into one, you can do it. You can even do `template 3` extends `template2` extends `template1`. – Shang Wang Jan 17 '16 at 04:32