How does template inheritance work?

Posted in Articles

Tweet This Share on Facebook Bookmark on Delicious Digg this Submit to Reddit

In this tutorial, we will explain how template inheritance work in the context of template engines such as Twig (see Twig getting-started tutorial).

We will use the example found on Sensiolabs Twig documentation reproduced here as allowed by Creative Commons Attribution-Share Alike 3.0 Unported License.

template inheritance

template inheritance

Here we see a parent template defined in base.html.   This template could be like the page of a website for example which most pages would use.  But the front page of the site might be slightly different and need to use another variant of the template, which we will call a child template.

The child template inherits from the parent template.  It does this with the “extends” tag indicating the parent file.

The parent template defines blocks with block tag and the name of block.  Four blocks are defined in the above example: head, title, content, footer.  The blocks starts with {% block %} and ends with {% endblock %}

In between are default content provided by the parent.  But the child can over-ride these by defining own blocks in the child template.  If child does not define a block (such as the footer block), then the parent’s footer block will render.

Within a block in the child template, the child can call {{ parent() }} which pulls in the content of the parent block.