模板中的url_for函数

模版中的url_for 跟我们后台视图函数中的url_for 使用起来基本是一模一样的。也是传递视图函数的名字,也
可以传递参数。使用的时候,需要在url_for 左右两边加上一个{{ url_for('func') }}

 

1、动态超链接

html页面使用如:
<a href="{{ url_for('login',p1='abc',p2='ddd',name='momo') }}">登录</a>
本质上就是动态路由
点击变为:
http://127.0.0.1:5000/accounts/login/momo/?p1=abc&p2=ddd

对应的视图函数:

@app.route('/accounts/login/<name>/')
def login(name):
print(name)
return render_template('login.html')

或者也可以不用动态路由:

html页面使用如:
<a href="{{ url_for('login',p1='abc',p2='ddd') }}">登录3</a>
点击变为:
http://127.0.0.1:5000/accounts/login/?p1=abc&p2=ddd

2、加载静态文件

静态文件:css文件 js文件 图片文件等文件
加载静态文件使用的是url_for 函数。然后第一个参数需要为static ,第二个参数需要为一个关键字参数
filename='路径' 。
语法:
{{ url_for("static",filename='xxx') }}

<link href="{{ url_for('static',filename='css/main.css') }}" rel="stylesheet">
<script src="{{ url_for('static',filename='js/main.js') }}"></script>
<img src="{{ url_for('static',filename='img/main.jpg') }}"/>

 

posted @ 2024-07-23 16:32  yongheng999  阅读(242)  评论(0)    收藏  举报