Multiple Template Inheritance, cannot inherit a block across multiple templates #1944
-
I'm working on a Flask application with Jinja templating. I have a base template (base.html) that defines several blocks for content and includes other templates like header.html, menu.html, and footer.html. Within MyPage.html, I'm extending the base.html and defining a block named test1 with some content (test1). However, the rendered output only shows "test1=" with no content. Here are the relevant code snippets: App.py
MyPage.html
base.html
header.html
hierarchy
I expected to see If I try to move Could you please tell me how to fix my code so that the block |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
I've created an example app based on what you've described, and I'm seeing the same result as you. I've looked over the docs and I can't find anything explaining the use of blocks with includes, but it's evident that blocks don't work with template includes. Template includes will work with template variables though. {% for box in boxes %}
{% include "render_box.html" %}
{% endfor %}
A Macro or a Context Processor is probably what you want to look into to solve the issue you're having. For example, you'd replace
<!DOCTYPE html>
<html>
{% block header %}{% endblock %}
<body>
... Then use a macro in
{% macro header(value) -%}
test1={{ value }}
{%- endmacro %}
{% import 'header.html' as header %}
...
{% block header %}
{{ header.header("hello") }}
{% endblock %} Note: You may need to test the code above, I wrote this on the train quickly and haven't tested it xD |
Beta Was this translation helpful? Give feedback.
I've created an example app based on what you've described, and I'm seeing the same result as you. I've looked over the docs and I can't find anything explaining the use of blocks with includes, but it's evident that blocks don't work with template includes.
Template includes will work with template variables though.
{{ box }}
will be able to be seen byrender_box.html
A Macro or a Context Processor is probably what you want to look into to solve the issue you're having.
For example, you'd replace
{% include 'header.html' %}
with a block:base.html