I use Flask to write web applications, and 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?
From flask documentation,
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.
Example
You could have
filename='...')
dynamically computed at runtime.Extending it further,
option enables redirection