Say I have a template layout saved in template.html. This template includes a banner, side navigation, content container, and footer. Can I use flask to break up these page elements in such a way that I can have files such as banner.html, sidenavigation.html, etc. and render these different files within template.html?
Asked
Active
Viewed 5.3k times
3 Answers
120
From: http://jinja.pocoo.org/docs/templates/#include
template.html
{% include 'banner.html' %}
{% include 'sidenavigation.html' %}
{% include 'content.html' %}
{% include 'footer.html' %}

edesz
- 11,756
- 22
- 75
- 123

Liyan Chang
- 7,721
- 3
- 39
- 59
-
1You might also want to look at Template Inheritance, as it might be a more powerful way of doing what you want: http://jinja.pocoo.org/docs/templates/#template-inheritance – Liyan Chang May 14 '12 at 22:03
-
1It should be noted that you can not create an inheritance hierarchy in Jinja2, you can only inherit a document one level deep. – Joshua Hedges Jul 21 '17 at 04:20
-
1@MadPumpkin: What exactly do you mean my that? You can extend as many levels deep as you want. It's not possible to extend a single template from multiple others (perhaps that is what you meant?) – Roy Prins May 31 '18 at 11:47
2
By default, Flask uses Jinja2 as its template engine. See Jinja's Template Designer Documentation how it's done.
-
But is it possible to highlight, which page is active in sidenavigation.html? – jOSe Nov 19 '20 at 05:54
-
@jOSe You can make use of the `scoped` keyword in the `block` definition within "sidenavigation.html". See Jinja's ["Block Nesting and Scope" section](https://jinja.palletsprojects.com/en/3.1.x/templates/#block-nesting-and-scope). Their example is `{% block loop_item scoped %}{{ item }}{% endblock %}` which allows `item` to pull its definition from the inheriting template. – John Crawford Mar 31 '22 at 20:45
1
Before you start, you need to write these components separately to other html files as pure html. For example, these files shouldn't contain any jinja syntax. After that, according to the documentation, you can easily import them into your template.html file by calling {% include 'filename.html' %}
code.

ned
- 61
- 1
- 5