Template structure

Matt Ramuta | 28 Dec 2014

It is very important to have a good template structure, which is easier to maintain. First of all you should create a base.html file, which would contain all of the code that you want to have in every html file (like head, navigation bar, footer). If your project is bigger and modular, you might also have “sub” base files in every module of your web app.

I mostly use Python on Google App Engine for my web development projects with Jinja2 as a templating engine. Jinja supports template hierarchy very well - here’s a simple example:


<!DOCTYPE html>
<html lang="en">
        <meta charset="utf-8">
        <title>{% block title %}{% endblock title %}</title>

        {% block maincontent %}{% endblock maincontent %}


{% extends “base.html” %}
{% block title %}My homepage{% endblock title %}
{% block maincontent %}
    <h1>Hello world!</h1>
{% endblock maincontent %}

As you probably figured out, Jinja uses blocks for html inheritance. That way you don’t have to write the whole html in your other (than base) html files, but only the code that makes that particular html file different from others. This approach helps you make your html files smaller and easy to maintain.