Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
520 views
in Technique[技术] by (71.8m points)

python - Why use Flask's url_for?

I'd like to know the reasoning behind using url_for to generate links in templates and the application code.

What do I gain by doing this:

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

and this:

<ul>
    <li><a href="{{ url_for('index') }}">Home</a></li> 
    <li><a href="{{ url_for('about') }}">About Us</a></li>
    <li><a href="{{ url_for('contact') }}">Contact</a></li>
</ul>

Instead of hard coding the paths?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

From Flask's documentation,

flask.url_for(endpoint, **values)

Generates a URL to the given endpoint with the method provided.

Variable arguments that are unknown to the target endpoint are appended to the generated URL as query arguments. If the value of a query argument is None, the whole pair is skipped. In case blueprints are active you can shortcut references to the same blueprint by prefixing the local endpoint with a dot (.).

Now, instead of specifying static urls to reach an endpoint, you can use url_for which does a reverse match for the endpoint. It is particularly useful when you have arguments which you might want to specify at runtime.

{{ url_for('events', user_id=user.id, year=2013) }}
/events/1388224/2013

The paths generated are always absolute (start with a "/") so that they work regardless of the current URL. They also take into account if the application is mounted at a prefix rather than the root (like "/myapp/events/1/2013").

The _external=True argument can be used to generate URLs with the server name so that they can be used externally, such as in email messages.

View your events: {{ url_for("events", user_id=user.id, year=2013, _external=True) }}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...