You will want to keep some global templates separate from your apps so that they are accessible across your website. The main examples of this are the constant in your pages such as a header, footer, and navigation section that will be on every page. Creating them in your root directory level templates folder lets you link them to your pages and include or extend them using the Django templating language. Keywords and functionality are explained further in the Django Templating Language section.
-
Include: Injects the whole HTML content into your page at that specific part of your HTML file where you
include it.
-
{% include "includes/navigation.html" %}
-
-
Extend: Inherits the template structure of the file. This can be seen as the inverse of Include, as you
will define 'blocks' in the file you extend and then define what fills them in your file that extends it.
-
The top of your page file that extends the base.html file will have
{% extends 'base.html' %} -
In the base.html file there will be
blocks
you can assign with any name such as
{% block blockname_1 %}{% endblock %}or{% block main_content %}{% endblock %} - In your file that extends the base.html file you will have these blocks defined with HTML between the start and end blocks that will appear in the section of that block on the base template
-
The top of your page file that extends the base.html file will have
A slightly less complicated way to look with a simple example.
- You will have a navigation.html file that has your navigation sections
- Your base template will include the navigation file and have sections (blocks) X, Y, and Z that are empty
- A new template e.g. in an app will extend the base template (which also has the navigation layout in it) and define what is shown in sections (blocks) X, Y, and Z
This theory can be extended for any reusable section of your website. For instance for code snippets in this website I have a template set up so that all I need to do is extend them and add the code so that they all keep the same layout without having to retype or copy the HTML for it each time.
The root level templates folder may look like:
-
templates
- base.html
- 404.html
-
includes
- navigation.html
- code_snippet.html