简体   繁体   中英

Flask redirect url with anchor

I have some problem with redirecting with anchors from python code.

My code:

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

This redirect didn't redirect me to #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 version 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'. Below is my attempt to do what you described.

views.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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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