Introduction to Jinja2 Templates
Key Concepts
- Template Engine
- Template Syntax
- Template Inheritance
Template Engine
Jinja2 is a powerful template engine for Python, commonly used with Flask. It allows developers to create dynamic HTML pages by embedding Python code within HTML. This separation of logic and presentation makes web development more organized and maintainable.
Template Syntax
Jinja2 uses a specific syntax to embed Python code within HTML. The syntax includes delimiters for variables, control structures, and comments. Here are the main delimiters:
{{ ... }}
: Used for embedding variables and expressions.{% ... %}
: Used for control structures like loops and conditionals.{# ... #}
: Used for comments.
For example, to display a variable in an HTML template:
<h1>Hello, {{ name }}!</h1>
In this example, {{ name }}
will be replaced with the value of the name
variable when the template is rendered.
Template Inheritance
Template inheritance is a powerful feature of Jinja2 that allows you to create a base template and extend it in child templates. This promotes code reuse and consistency across different pages of your website.
For example, a base template named base.html
might look like this:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>{% block title %}My Website{% endblock %}</title> </head> <body> <header> <h1>Welcome to My Website</h1> </header> <main> {% block content %}{% endblock %} </main> <footer> <p>© 2023 My Website</p> </footer> </body> </html>
A child template named home.html
can extend this base template and override the blocks:
{% extends "base.html" %} {% block title %}Home{% endblock %} {% block content %} <h2>Welcome to the Home Page</h2> <p>This is the content of the home page.</p> {% endblock %}
In this example, home.html
inherits the structure from base.html
and overrides the title
and content
blocks to customize the page.