Extending templates - 30 days of Django

Extending templates - 30 days of Django

/ #Django

One of Djangos most important thing is that you shouldn't repeat your self. So in this part, we learn how to reuse parts of a template.

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>

            The menu

            The footer

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>
{% 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


No comments yet...

Add comment


Subscribe to my weekly newsletter. One time per week I will send you a short summary of the tutorials I have posted in the past week.