DEV Community

Schleidens.dev
Schleidens.dev

Posted on

Django root base template setup

If you're learning django you may be familiar with the {% extends base.html %} pattern but what if you want all your apps in your project to use the same base template

Django provides a way of making a parent template to not repeat the same piece of code in every template "the DRY pattern (Don't repeat yourself)" .
Let's consider you have a Navbar and a Footer, you can make a base.html template with them and use it in all your templates.

your_project/your_app/templates/base.html

<!DOCTYPE html>
<html>
<head>
  <title>Mamamiahh</title>
</head>
<body>

<!-- Navbar start -->
<div>
  <ul>
    <li><a href="default.asp">Home</a></li>
    <li><a href="news.asp">News</a></li>
    <li><a href="contact.asp">Contact</a></li>
    <li><a href="about.asp">About</a></li>
  </ul> 
</div>
<!-- Navbar end -->

{% block content %}
{% endblock %}


<!-- Footer start -->
<div>
 <p> I'm the footer </p>
</div>
<!-- Footer end -->

</body>
</html>
Enter fullscreen mode Exit fullscreen mode

You notice the {% block content %} and {% endblock %} they are placeholders, telling Django to replace this block with content from other sources.

Now you can use your base.html with all your template.
let's do it !!

your_project/your_app/templates/home.html

{% extends "base.html" %}

{% block content %}
  <p>In HTML, spaces and new lines are ignored:</p>

<p>

  My Bonnie lies over the ocean.

  My Bonnie lies over the sea.

  My Bonnie lies over the ocean.

  Oh, bring back my Bonnie to me.

</p>
{% endblock %}
Enter fullscreen mode Exit fullscreen mode

Now home.html can use the base template, this is done by including the base template with the {% extends %} tag.

Good !! but what if you want all your apps template to use the same base.html

First create a template folder in your root project and add base.html
your_project/templates/base.html
Open settings.py and find this piece of code
settings.py screenshot

When APP_DIRS is set to True , Django automatically finds the templates/ directory when it's located in an app. However, as we are placing the base template at the project root, you need to specify it in settings.py for Django to find this directory.

Edit settings.py

Now your base.html is ready to use in all your apps, all you need to do is extend it in your templates by using the extends tag {% extends "base.html" %}

Siahhhhhhhh in another blog about django :)

Top comments (0)