016-Django Master Template

Objectives: Django Master Template

Django Master Template

Django Master Template

1. Create the Master Template

Create master.html in the templates folder:

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

{% block content %}{% endblock %}

</body>
</html>

Tip:

The {% block %} tag defines placeholders that child templates can fill with content.

2. Modify all_members.html

Extend the master template and define blocks:

{% extends "master.html" %}

{% block title %}
  My Tennis Club - List of all members
{% endblock %}

{% block content %}
  <h1>Members</h1>

  <ul>
    {% for x in mymembers %}
      <li><a href="details/{{ x.id }}">{{ x.firstname }} {{ x.lastname }}</a></li>
    {% endfor %}
  </ul>
{% endblock %}

3. Modify details.html

Extend the master template and define blocks for the details page:

{% extends "master.html" %}

{% block title %}
  Details about {{ mymember.firstname }} {{ mymember.lastname }}
{% endblock %}

{% block content %}
  <h1>{{ mymember.firstname }} {{ mymember.lastname }}</h1>
  <p>Phone: {{ mymember.phone }}</p>
  <p>Member since: {{ mymember.joined_date }}</p>
  <p>Back to <a href="/members">Members</a></p>
{% endblock %}

Example:

Both templates now share the same layout from master.html. Any future updates to the header or body structure can be done in one place.

4. Start the Server

Run the server:

python manage.py runserver

Open 127.0.0.1:8000/members/ in your browser to see the templates using the master template.

Advice:

  • Use a master template to keep your site layout consistent.
  • Always define blocks in the master template for content that changes per page.
  • This makes maintaining multiple pages easier and avoids repeating HTML code.

Reference Book: N/A

Author name: SIR H.A.Mwala Work email: biasharaboraofficials@gmail.com
#MWALA_LEARN Powered by MwalaJS #https://mwalajs.biasharabora.com
#https://educenter.biasharabora.com

:: 1::