refactor html templates using base.html

Date: March 22nd 2016
Last updated: March 22nd 2016

A single html template is rendered for each method in views.py. Duplication can occur quickly if the same content is recycled between templates. The solution is to create a base level html file that can be added to.

The purpose of this example is to create a header once that is used on many html pages.

Create base.html
The content that is added will fall between and .

{% load staticfiles %}
<html>
  <head>
      <link rel="stylesheet" type="text/css"
            href="{% static 'surferprofile/style.css' %}" />
  </head>
  <body>
      <header>
          <div id="logo">SURFDIARY</div>
          <div class="headermenu">Logout</div>
          <div class="headermenu">Groups</div>
          <div class="headermenu">Stats</div>
          <div class="headermenu">Alerts</div>
      </header>

      {% block body_block %}{% endblock %}

  </body>
 </html>

Modify diary.html
Note here the call to extend base.html with the content from diary.html. The content that is inserted falls between the body_block and endblock statements.

{% extends 'surferprofile/base.html' %}

{% block body_block %}
    <div id="diarycontainer">
      <div>
          This is a diary entry for <strong>{{ surfer.firstname }}</strong>
      </div>
        {% if surfdiary %}
          <table id='diarytable'>
              <tr id='diarytitlerow'>
                  <td>Beach</td>
                  <!---- <snipped> ---->
              </tr>

            {% for entry in surfdiary %}
              <tr>
                  <td>{{ entry.beach }}</td>
                  <!---- <snipped> ---->                  
              </tr>
          {% endfor %}
          </table>
      {% else %}
          <p>No diary entries.</p>
      {% endif %}
</div>

{% endblock %}

http://127.0.0.1:8080/1/diary/

results matching ""

    No results matching ""