How do I include a HTML file in a Jinja2 template?

PythonHtmlFlaskJinja2

Python Problem Overview


I am using Flask micro-framework for my server which uses Jinja templates.

I have a parent template.html and some children templates called child1.html and child2.html, some of these children templates are pretty large HTML files and I would like to somehow split them for better lucidity over my work.

Contents of my main.py script:

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>

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.

I'd like to just load the content1.html instead of writing it all in child1.html.

I came across this question, 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 illustrate the problem.

Python Solutions


Solution 1 - Python

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.

Solution 2 - Python

You can use the include statement.

Solution 3 - Python

I'd like to add the proper syntax for using include, one given above works fine, but when it comes to the path, it took some time to find this, it is not even mentioned in the official document.

Syntax for include is:

{% include 'path_to_template_file' %}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionquapkaView Question on Stackoverflow
Solution 1 - PythonmsvalkonView Answer on Stackoverflow
Solution 2 - PythonjarandafView Answer on Stackoverflow
Solution 3 - PythonSinghView Answer on Stackoverflow