How to include templates | Django

/ #Django


Template inheritance is a powerful feature of Django's templating system that allows you to build a base skeleton template that contains all the common elements of your site and defines blocks that child templates can override.

This allows you to build a consistent site layout and ensures that you don't have to repeat the same code in multiple templates.

To create a template in Django, you will need to create a template directory in your Django app and put your templates inside it. Django will automatically find and use templates in this directory when you use the render() function in your views.

To create a base template, you can use the extends tag to specify the parent template that your template will inherit from. For example, you might create a base template called base.html that looks something like this:

<!DOCTYPE html>
<html>
  <head>
    {% block head %}
    <title>My Site</title>
    {% endblock %}
  </head>
  <body>
    {% block content %}
    {% endblock %}
  </body>
</html>

This template defines two blocks: head and content. Child templates can override these blocks by using the block tag. For example, you might create a child template called home.html that looks like this:

{% extends "base.html" %}
{% block head %}
  <title>Home</title>
{% endblock %}
{% block content %}
  <h1>Welcome to my site!</h1>
  <p>Here's some content.</p>
{% endblock %}

To include this template in your Django view, you would use the render() function and pass it the request object and the name of the template you want to use. For example:

from django.shortcuts import render

def home(request):
    return render(request, "home.html")

When Django renders this view, it will find the home.html template and use it to render the response. The home.html template will inherit from the base.html template and override the head and content blocks to create the final HTML that is sent to the client.

I hope this helps! Let me know if you have any questions.

Comments

Edward David Thoronka | Oct 17, 24 04:51

That Stein, I am having a problem with Template inheritance, I have created the template directory and also used the extends keyword on the base directory but it doesn't work, Is there any way to solve it? I am following one of your tutorials "Learn Django by Building an Online Marketplace Python Tutorial for Beginners"


Stein Ove Helset | Oct 17, 24 05:18

Hey, it's hard to say without knowing exactly what you've typed in your code. I usually put my base.html in an app called core where I also have pages like about, contact, etc..

Add comment

Info

Please log in to comment!

Newsletter

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.