A few days ago, we created our first Django template. But it lacks many things. A valid HTML page at least needs the html-tag, the head-tag and the body-tag. But we don't want to keep writing these for all the templates we create. The solution to this is to extend templates.
In other words, we create a base template with the necessary html-tags. Plus, we add the menu there, the footer and similar.
Let's begin by making a new file called base.html inside the template folder (the same folder where frontpage.html is located). It should look like this:
<!doctype html>
<html>
<head>
<title>Toodoo</title>
</head>
<body>
<nav>
The menu
</nav>
<footer>
The footer
</footer>
</body>
</html>
Okay, it's not very impressive yet... But anyways, let's make it possible for the frontpage.html to extend this template now. We want to make it possible to insert data between the nav and the footer. To do this, we add something called a tag-block:
{% block content %}
{% endblock %}
The name "content" is something that's typically used for the main content (title, texts, images and similar). We'll add more later.
Then, the next step is to make sure that the frontpage.html is using this template. The frontpage.html file should look like this:
{% extends 'task/base.html' %}
{% block content %}
<div class="frontpage">
<h1>{{ title }}</h1>
<p>This is just a hard coded paragraph!</p>
</div>
{% endblock %}
The first change here is the "extends" tag. We just say to the rendering engine that we want to extend "this" html file and points to the base.html file. Below, we add the same block tag as in the base file to tell Django where to put the content inside.
If you open the website in your browser again, it should now look a little bit different. There should now be a "nav" and a "footer" as well. Now it is much easier to add more pages to our project. And if we want to change the menu, the only file we need to change is the base.html.
Django templates also has a lot of other cool features. Like functionality for looping, testing and so much more.
Table of contents
- 1. Introduction
- 2. Installation and setup
- 3. How things work
- 4. The first Django app
- 5. Your first view
- 6. Your first template
- 7. Testing our site
- 8. Extending templates
- 9. Your first model
- 10. The admin interface
- 11. Showing contents from the model
- 12. Another app (category)
- 13. Connecting two models
- 14. Show list of categories
- 15. Category detail page