Flaskrender_template详解

发布时间:2023-05-19

Flask是Python中极为流行的Web框架之一,它为开发者提供了简单易用的工具,使得建立Web应用变得异常容易。而Flask中,render_template函数是应用最多的函数之一。在这篇文章中,我们将详细探讨Flask中的render_template函数。

一、基本介绍

在Flask应用程序中,render_template函数在模板中渲染HTML文件并将结果发送回浏览器。参数包括文件名和要在HTML文件中使用的数据。这些数据必须以变量的形式传递,并在模板中使用。下面是一个例子:

from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def index():
   return render_template('index.html')
@app.route('/hello')
def hello():
   name = "John"
   return render_template('hello.html', name=name)
if __name__ == '__main__':
   app.run()

在上述例子中,我们定义了两个路由://hello/路由将调用名为index.html的模板文件,而/hello路由将调用名为hello.html的模板文件。另外,我们向hello.html传递了一个变量name

二、使用模板文件

在Flask中使用render_template函数时,需要先定义一个模板文件,以便将数据呈现为HTML页面。模板文件通常位于名为templates的目录下。在下面的示例中,我们为Hello World应用程序创建了一个名为hello.html的模板文件:

<title>Hello {{ name }}</title>
<h1>Hello {{ name }}</h1>