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?
From: http://jinja.pocoo.org/docs/templates/#include
template.html
{% include 'banner.html' %}
{% include 'sidenavigation.html' %}
{% include 'content.html' %}
{% include 'footer.html' %}
By default, Flask uses Jinja2 as its template engine. See Jinja's Template Designer Documentation how it's done.
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 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.
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
© 2022 - 2024 — McMap. All rights reserved.