Matt Ramuta

28 December 2014

Template structure

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:

base.html

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

    <body>
        {% block maincontent %}{% endblock maincontent %}
    </body>
</html>

home.html

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


# Back