Flask url_for() vs. hard coding the path

It seems like the codecademy course on flask prefers using url_for() instead of hard coding the path into the html file.

<a href='{{ url_for("index") }}'></a>

seems to be equivalent to:

<a href="/index"></a>

if so, what are the benefits of using url_for()?

Besides being more efficient when changing the root, when you want your page calls to more dynamic.

print(url_for('profile', user='Serena Williams'))

can easily be

print(url_for('profile', user=current_user))

and so your link will vary depending on the relevant user in the second example.

1 Like

Can’t this be done like so:

print("/profile/{{ current_user }}")

See the earlier comment about the root. So it has multiple angles for flexibility.

For example, if you have 10 different pages with instances of this link, if you want to change the link, you have to change it 10 times. If you use a url_for, you just have to change the one link.

Another way you can tackle this is seeing all the things that can be done with a url_for (through examples maybe) and trying to see how much work it would take to do it in plan html.

Can you show an example for this in code? I’m having trouble understanding it.

I can’t whip up a representative one right this moment, but google is your friend here, there’s plenty around :slight_smile:

@thunder_coder check Miguel Grinberg and Corey Schaffer’s stuff. They have a lot of good examples of flask code. (The former also has a great book on it).
They have videos but also links to their githubs for this.

1 Like