How to pass multiple templates to flask.render_template()

Question:

I’m trying to deploy a flask app and I want a flask.render_template() method passed with a list of html files. Here I see it’s eligible. http://flask.pocoo.org/docs/0.12/api/#flask.render_template

I’m trying with this code

from flask import Flask, render_template
app = Flask(__name__)
app.debug = True

@app.route('/')
def hello():
    templs = ["_header.html", "_footer.html"]
    return render_template(templs)

if __name__== '__main__':
    app.run()

But actually server returns only the first template from the list.
How to iterate though this list in order to render all templates from the list?

Thanks,
Alex

Asked By: Alexey Pchelnikov

||

Answers:

As far as i see you are trying to render static header and footer. I’d recommend to prepare something like “layout.html” with included header and footer:

//layout.html
<html>
    <head>//headhere</head>
    <header>//your static header</header>
    <main>
        {% block body %}
        //content will be here
        {% endblock %}
    </main>
    <footer> //your static footer </footer>
</html>

then in “child” templates(ex: index.html)use:

//index.html
{% extends "layout.html" %}
{% block body %}
   //your code here
{% endblock %}

It will render header and footer from layout.html and rest from index.html.

Answered By: How about nope

You probably don’t want to render multiple templates. What you want is to render one template that combines multiple templates. That is the task of templating engine, not Flask. See http://jinja.pocoo.org/docs/dev/templates/ (Flask uses Jinja).

Answered By: jbasko

Exactly like @jbasko wrote!
Making use of two {{block}} statements worked for me:
For example, I put in my routes.py

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

the page1.html is containing simply two block-specifications

{% extends "page1.html" %}
{% block content %}  
<h1> Content </h1>
{% endblock content %}

{% block info %}
<h1> Info </h1>
{% endblock info %}

which gets referenced in layout.html in two separate places:

 {% block content %}{% endblock %}

and later

 {% block info %}{% endblock %}

Thanks for the help everyone!

Answered By: Simon Stolz

you can try this…

from flask import Flask, render_template
app = Flask(__name__)
app.debug = True

@app.route('/')
def hello():
   render_header = render_template('_header.html')
   render_footer = render_template('_footer.html')
   return render_header + render_footer

if __name__ == '__main__':
   app.run()
Answered By: Vishnu T s
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.