7. Base Template
Django is detailed about generating output from a model. Or, can I say, involved? Anyway, if you intend to output webpages, then most sites will want to wrap pages in a generic HTML template.
Base template folder
It’s a folder in a folder. Create,
Make a base template
The following is generic. It includes blocks for CSS, JavaScript and ‘content’. Adapt as you wish—for example, you may wish to include site‐wide CSS/JS, or a more complete HTML framework with headers/footers/sidebars etc. In siteName/templates/base.html,
Register the base template
In siteName/settings.py…
First, this is useful (I suggested this in Step 2). Add it,
Now modify the TEMPLATES > DIRS setting to include the global template folder,
Template partials and inheritance
I’m not going into it here, but the Django template system can build templates from partial templates, which describe part of the page. You place ‘blocks’ inside the the templates, that can be filled later by other templates.
You can also, in a less pre‐planned way, import a template into other templates. This is useful for reusable template snippets. It looks like this,
For an ‘include’ the path is a regular Python/Unix path from the template source e,g, ”../../sitename/template_snippet.html” is a valid path.
Note that if you do not use inverted commas, “string” syntax, then the template thinks you are referring to a variable on the supplied object,
This may be useful if, for example, an object is passed that can render itself, or has HTML included. But it is also a way to be misunderstood.
If you wish to exploit these features fully, I’ve written an article on Django template interactions.
Refs
Template inheritance, Django documentation.
https://docs.djangoproject.com/en/3.2/ref/templates/language/#template-inheritance
Template inclusion, Django documentation,
https://docs.djangoproject.com/en/3.2/ref/templates/builtins/#std:templatetag-include