Include html file in Jinja2 template

I am using Flask microframework for my server which uses Jinja templates. I have parent template.html and some childs child1.html, child2.html. Some of these childs are pretty large html files and I would like to somehow split them for better lucidity over my work.

the main.py:

    from flask import Flask, request, render_template

    app = Flask(__name__)

    @app.route('/')
    @app.route('/<task>')
    def home(task=''):
        return render_template('child1.html', task=task)

    app.run()

The simplified template.html:

    <!DOCTYPE html>
    <html>
    <head>
    </head>
    <body>
        <div class="container">
            {% block content %}
            {% endblock %}
        </div>
    </body>
    </html>

And the magic is in child1.html:

    {% extends 'template.html' %}
    {% block content %}
        {% if task == 'content1' %}
            <!-- include content1.html -->
        {% endif %}
        {% if task == 'content2' %}
            <!-- include content2.html -->
        {% endif %}
    {% endblock %}

Instead of the comments

    <!-- include content1.html -->

I have a lot of html text. And it is very hard to keep track of changes and not to make some mistakes, which are then pretty hard to find and correct. So I would like to just load the content1.html instead of writing it all in child1.html. I came across this question Include another HTML file in a HTML file , but I had problems implementing it. I think Jinja2 might have a better tool for that.

Note. The code above might not be working properly, I just wrote it to ilustrate the problem.

Use the jinja2 {% include %} directive.

    {% extends 'template.html' %}
    {% block content %}
        {% if task == 'content1' %}
            {% include 'content1.html' %}
        {% endif %}
        {% if task == 'content2' %}
            {% include 'content2.html' %}
        {% endif %}
    {% endblock %}

This will include the content from the correct content-file.

From: stackoverflow.com/q/22860085

Back to homepage or read more recommendations: