使用uri()函数在Python的Mako模板中生成URL
发布时间:2023-12-14 06:30:06
在Python的Mako模板中,可以使用uri()函数来生成URL。该函数接受一个或多个参数,其中第一个参数是视图函数的名称或视图函数的路径,其余参数可以是路由中定义的变量。
下面是一个使用uri()函数生成URL的示例:
# app.py
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/users/<username>')
def user(username):
return render_template('user.html', username=username)
if __name__ == '__main__':
app.run()
<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
<title>Home</title>
</head>
<body>
<h1>Welcome to the Home page!</h1>
<p><a href="${uri('user', username='John')}">Visit John's profile</a></p>
<p><a href="${uri('user', username='Jane')}">Visit Jane's profile</a></p>
</body>
</html>
<!-- user.html -->
<!DOCTYPE html>
<html>
<head>
<title>User Profile</title>
</head>
<body>
<h1>User: ${username}</h1>
<p>This is ${username}'s profile</p>
</body>
</html>
在上面的示例中,我们定义了两个路由/和/users/<username>,分别对应index()和user()视图函数。index()函数渲染了index.html模板,其中使用了uri()函数生成了两个链接,分别指向user.html模板,并传递了用户名作为参数。
在user.html模板中,我们使用${username}输出了传递的参数值。
启动应用程序后,访问http://localhost:5000将显示首页,其中有两个链接可以访问用户的个人资料页,分别对应用户"John"和"Jane"。点击这些链接将导航到相应的用户个人资料页,URL中将带有用户名作为参数。
这就是在Python的Mako模板中使用uri()函数生成URL的一个示例。可以根据实际需求,根据路由定义和视图函数进行适当的调整和扩展。
