Jinja Base Template
n
The base template is the foundation of Jinja’s template inheritance system. It serves as a skeleton for your website, defining the common layout and boilerplate code that is shared across multiple pages. This includes elements like the DOCTYPE, the “, “, and “ tags, and shared components such as a header, footer, or navigation bar. By centralizing this shared structure, you can make site-wide changes from a single file, which greatly simplifies maintenance and ensures consistency.
nn
Example: base.html
n
This template, which we’ll call base.html, defines a simple HTML skeleton document that you might use for a simple two-column page. It’s the job of “child” templates to fill the empty blocks with content:
nn
<!DOCTYPE html>n<html lang="en">n<head>n {% block head %}n <link rel="stylesheet" href="style.css" />n <title>{% block title %}{% endblock %} - My Webpage</title>n {% endblock %}n</head>n<body>n <div id="content">{% block content %}{% endblock %}</div>n <div id="footer">n {% block footer %}n © Copyright 2008 by <a href="http://domain.invalid/">you</a>.n {% endblock %}n </div>n</body>n</html>
n
In this example, the {% block %} tags define four blocks that child templates can fill in. All the block tag tells the template engine that a child template may override those placeholders in the template. It’s important to note that block tags can be inside other blocks, such as if statements, but they will always be executed regardless of whether the if block is rendered. This behavior ensures that the template engine correctly identifies all possible override points, even if they are nested within control flow logic.
nn
n
