简体   繁体   English

带锚点的 Flask 重定向 url

[英]Flask redirect url with anchor

I have some problem with redirecting with anchors from python code.我在使用 python 代码中的锚重定向时遇到了一些问题。

My code:我的代码:

func():
    ...
    redirect(url_for('my_view', param=param, _anchor='my_anchor'))

This redirect didn't redirect me to #my_anchor.此重定向没有将我重定向到 #my_anchor。

In template link like:在模板链接中,如:

<a href="{{ url_for('my_view', param=param, _anchor='my_anchor') }}"></a>

works good... May be problem in flask function "redirect".效果很好......烧瓶功能“重定向”可能有问题。

How I can use redirect with anchors in Flask?如何在 Flask 中使用带有锚点的重定向?

Flask version 0.10.x烧瓶版本 0.10.x

if your goal is to be redirected to a page with an anchor preselected in the url I think the problem may be connected to the function you have passed in the 'url_for'.如果您的目标是重定向到在 url 中预选了锚点的页面,我认为问题可能与您在“url_for”中传递的函数有关。 Below is my attempt to do what you described.下面是我尝试做你所描述的。

views.py视图.py

from flask import Flask
from flask import redirect, url_for
app = Flask(__name__)


@app.route('/')
def hello_world():
    return 'Hello World!'


@app.route('/myredirect')
def my_redirect():
    return redirect(url_for('hello_world',_anchor='my_anchor'))


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

This does not need a template, as as soon as you hit /myredirect you are redirected to / with anchor #my_anchor这不需要模板,只要你点击 /myredirect,你就会被重定向到 / 锚点 #my_anchor

After you get your views started with $ python views.py and navigate to http://127.0.0.1:5000/myredirect you end up on http://127.0.0.1:5000/#my_anchor在您以$ python views.py开始您的视图并导航到http://127.0.0.1:5000/myredirect 后,您最终会访问http://127.0.0.1:5000/#my_anchor

A short and simple way of doing this is一个简短而简单的方法是

return redirect(url_for('hello_world') + '#my_anchor')

instead of代替

return redirect(url_for('hello_world',_anchor='my_anchor'))

which works because url_for returns a string for the endpoint.这是有效的,因为url_for返回端点的字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM