Understanding Nested Template Examples
n
nnTo truly grasp the power of Jinja’s nested inheritance, let’s look at some practical examples that demonstrate the parent-child-grandchild relationships. This layered approach is perfect for building scalable websites where different pages need a common base but also specific layouts.nn
nn
nn
n
A Simple Inheritance Chain
nConsider a three-level hierarchy: parent.tmpl, child.tmpl, and two different grandchild templates.n
- n
parent.tmpl: This is the top-level template that sets the foundation. It contains abodyblock with a simple default message.n# parent.tmplnbody: {% block body %}Hi from parent.{% endblock %}child.tmpl: This template extendsparent.tmpl. Within itsbodyblock, it adds its content (“Hi from child.”) and then uses{{ super() }}to pull in the content from the parent’sbodyblock (“Hi from parent.”).n# child.tmpln{% extends "parent.tmpl" %}n{% block body %}Hi from child. {{ super() }}{% endblock %}grandchild1.tmpl: This template extendschild.tmpl. It simply overrides thebodyblock with its content (“Hi from grandchild1.”) and doesn’t usesuper(). When rendered, it will completely replace the content of both the parent and child blocks.n# grandchild1.tmpln{% extends "child.tmpl" %}n{% block body %}Hi from grandchild1.{% endblock %}grandchild2.tmpl: This template also extendschild.tmpl. However, it uses a chainedsuper()call:{{ super.super() }}. This skips the immediate parent’s (the child’s) content and directly fetches the content from the grandparent template (parent.tmpl).n# grandchild2.tmpln{% extends "child.tmpl" %}n{% block body %}Hi from grandchild2. {{ super.super() }} {% endblock %}
n
n
n
n
n
nn
nn
n
The Final Rendered Output
nThe beauty of this system is in the final result. grandchild1.tmpl will render only Hi from grandchild1. because it completely overrides the block. In contrast, grandchild2.tmpl will render “Hi from grandchild2. Hi from parent.” because it specifically requested the grandparent’s content. These examples highlight how Jinja’s flexible block system and super() function give you granular control over template composition, allowing you to build complex and modular layouts with minimal code duplication.nn
n
