How to Use Include in Jinja2 Templates with Flask
In Flask, you use the
{% include 'filename.html' %} statement inside Jinja2 templates to insert the content of another template file. This helps you reuse common HTML parts like headers or footers across multiple pages easily.Syntax
The {% include 'filename.html' %} statement tells Jinja2 to insert the content of the specified template file at that position. The filename should be a string with the relative path to the template file inside your templates folder.
- {% include %}: Jinja2 directive to include another template.
- 'filename.html': The template file to include, in quotes.
jinja2
{% include 'header.html' %}Example
This example shows a Flask app rendering a main template that includes a header and footer template using {% include %}. It demonstrates how to reuse common HTML parts.
python
from flask import Flask, render_template app = Flask(__name__) @app.route('/') def home(): return render_template('main.html') if __name__ == '__main__': app.run(debug=True) # templates/header.html # <header><h1>Welcome to My Site</h1></header> # templates/footer.html # <footer><p>© 2024 My Site</p></footer> # templates/main.html # <html> # <body> # {% include 'header.html' %} # <p>This is the main content.</p> # {% include 'footer.html' %} # </body> # </html>
Output
<html>
<body>
<header><h1>Welcome to My Site</h1></header>
<p>This is the main content.</p>
<footer><p>© 2024 My Site</p></footer>
</body>
</html>
Common Pitfalls
- Forgetting to put the included file inside the
templatesfolder causes aTemplateNotFounderror. - Using incorrect quotes or missing quotes around the filename will cause a syntax error.
- Including templates that expect variables without passing them can cause errors or missing data.
- Trying to include templates with absolute paths instead of relative paths inside the templates folder will fail.
jinja2
{% include header.html %} <!-- Wrong: missing quotes -->
{% include 'header.html' %} <!-- Correct: quotes included -->Quick Reference
Use {% include 'file.html' %} to insert reusable template parts. Always keep included files in the templates folder. Use quotes around filenames. Pass variables if needed using with keyword.
jinja2
{% include 'sidebar.html' with context %}Key Takeaways
Use {% include 'filename.html' %} to reuse template parts in Jinja2 with Flask.
Always place included templates inside the templates folder and use quotes around filenames.
Including templates helps keep your HTML organized and avoids repetition.
Watch out for missing quotes or wrong file paths to prevent errors.
You can pass variables to included templates using the with keyword if needed.