Skip to main content
 首页 » 编程设计

python之如何将多个模板传递给 flask.render_template()

2025年05月04日2598°冷暖

我正在尝试部署一个 flask 应用程序,我想要一个带有 html 文件列表的 flask.render_template() 方法。在这里,我看到它是合格的。 http://flask.pocoo.org/docs/0.12/api/#flask.render_template

我正在尝试使用这段代码

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() 

但实际上服务器只返回列表中的第一个模板。 如何遍历此列表以呈现列表中的所有模板?

谢谢, 亚历克斯

请您参考如下方法:

据我所知,您正在尝试呈现静态页眉和页脚。我建议准备类似“layout.html”的内容,其中包含页眉和页脚:

//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> 

然后在“子”模板中(例如:index.html)使用:

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

它将从 layout.html 渲染页眉和页脚,从 index.html 渲染 rest。