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>
    {% block head %}
    <title>My Site</title>
    {% endblock %}
    {% block content %}
    {% endblock %}

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


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.