How to use Django's built-in template tags for template inheritance



Image not found!!

Django's template inheritance is a powerful feature that allows you to create a base template and extend it in other templates. This is particularly useful for maintaining a consistent layout across multiple pages in a web application. To use Django's built-in template tags for template inheritance, you can follow these steps:

  1. Create a Base Template:

    Start by creating a base template that contains the common structure and elements shared across multiple pages. For example, create a file named base.html:

    html
    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>{% block title %}My Website{% endblock %}</title> </head> <body> <header> <h1>{% block header %}Welcome to My Website{% endblock %}</h1> </header> <nav> <!-- Navigation links go here --> </nav> <main> {% block content %}{% endblock %} </main> <footer> <!-- Footer content goes here --> </footer> </body> </html>
  2. Extend the Base Template:

    In other templates, you can extend the base template using the {% extends %} tag and override specific blocks using the {% block %} tag. Create a new template, e.g., home.html:

    html
    {% extends 'base.html' %} {% block title %}Home - My Website{% endblock %} {% block header %}Welcome to the Home Page{% endblock %} {% block content %} <p>This is the home page content.</p> {% endblock %}

    In this example, the home.html template extends the base.html template and overrides the title, header, and content blocks.

  3. Render the Template in Views:

    In your Django views, render the extended template using the render function:

    python
    from django.shortcuts import render def home(request): return render(request, 'home.html')

    Ensure that your Django app is configured properly, and the home view is mapped to a URL.

  4. Run the Development Server:

    Start the development server and navigate to the URL associated with the home view. You should see the content of the home.html template rendered within the structure of the base.html template.

Template inheritance in Django allows you to maintain a modular and DRY (Don't Repeat Yourself) code structure by separating common elements into a base template and extending it in specific templates as needed.