2

I need to pass block from base template to included template with context, but don't want
overlapping of this blocks in base template. For example, I have couple templates

header.html

<header>
    <title>{% block title %}{% endblock %}</title>
</header>

body1.html

{% include   "test_header.html" ignore missing with context %}
{% block title %}Title1{% endblock %}
<body>
    Hello
</body>

body2.html

{% include   "test_header.html" ignore missing with context %}
{% block title %}Title2{% endblock %}
<body>
    Hello
</body>

When I try to render body1.html, title of page renames to "Title1", but block title renders twice and shows Title1 in body. How I can pass this context exactly for include statement?

Skiv_mag
  • 284
  • 1
  • 4
  • 13
  • 1
    Generally speaking, you have a use case of `extends`, not `include`. I'd create a `base.html` with included `header.html`. Then I'd extend body1 and body2 from base. – alecxe Aug 22 '13 at 08:07

2 Answers2

2

The method to include dynamic content like the title is usually {{ ... }}, while {% ... %} is for control statements (for loops, if statements, blocks, etc). You might construct your specific templates like the following:

base.html

<html>
<head>
    <title>{{title}}</title>
</head>
<body>
    {% block body %}{% endblock %}
</body>
</html>

As stated by @alecxe, you should extends off a base template.

body1.html

{% extends "base.html" %}

{% block body %}
Hello!
{% endblock %}

body2.html

{% extends "base.html" %}

{% block body %}
Hi!
{% endblock %}

The title should be passed to the template with render_template() in the view.

view.py excerpt

@app.route('/body1')
def body1():
    title = "Body 1 Title"
    return render_template("body1.html", title = title)

@app.route('/body2')
def body2():
    title = "Body 2 Title"
    return render_template("body2.html", title = title)

If you greatly wanted to vary the header between templates, you could also replace <title>{{title}}</title> with {% block header %}{% endblock %} in base.html. Your body1.html could then look like this:

{% extends "base.html" %}

{% block header %}
<title>{{title}}</title>
{% endblock %}

{% block body %}
Hello!
{% endblock %}
Seberius
  • 399
  • 2
  • 6
0

Blocks don't work in included templates. They are only valid in child / parent template relationships. How about something like...

sections.html

{% with section_data=section_data %}
{% include 'section.html' %}
{% endwith %}

section.html:

{% for section in section_data %}
  <h2>{{ section.title }}</h2>
  <div>
    {{ section.content }}
  </div>
{% endfor %}

See: How to pass selected, named arguments to Jinja2's include context?

Source: https://www.reddit.com/r/flask/comments/b7eh21/how_do_i_pass_blocks_or_information_into_an/

Zaffer
  • 1,290
  • 13
  • 32