Is it possible to perform Includes with flask?
Asked Answered
R

4

62

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?

Riehl answered 13/3, 2012 at 5:55 Comment(0)
W
123

From: http://jinja.pocoo.org/docs/templates/#include

template.html

{% include 'banner.html' %}
{% include 'sidenavigation.html' %}
{% include 'content.html' %}
{% include 'footer.html' %}
Whimsicality answered 14/5, 2012 at 22:3 Comment(3)
You might also want to look at Template Inheritance, as it might be a more powerful way of doing what you want: jinja.pocoo.org/docs/templates/#template-inheritanceWhimsicality
It should be noted that you can not create an inheritance hierarchy in Jinja2, you can only inherit a document one level deep.Tabbie
@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?)Enloe
K
2

By default, Flask uses Jinja2 as its template engine. See Jinja's Template Designer Documentation how it's done.

Kalikalian answered 13/3, 2012 at 10:48 Comment(2)
But is it possible to highlight, which page is active in sidenavigation.html?Hitherward
@Hitherward You can make use of the scoped keyword in the block definition within "sidenavigation.html". See Jinja's "Block Nesting and Scope" section. Their example is {% block loop_item scoped %}{{ item }}{% endblock %} which allows item to pull its definition from the inheriting template.Amabelle
S
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.

Sardou answered 17/1, 2022 at 21:25 Comment(0)
A
0

Think carefully about whether to use inheritance (extends) vs composition (include).

If you have several pages with nearly identical structure, inheritance may be the best choice. But if you are 'planning for change', composition may be more flexible, and only slightly longer.

It's common for folks new to object-orientation to overuse inheritance. See "Uncle Bob" on the question, at https://twitter.com/unclebobmartin/status/1308029538463625219?lang=en

Albertalberta answered 20/2 at 19:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.