top of page

How to use url_for in Flask

Flask provides an easy way to dynamically auto-generate href paths in your HTML files using the url_for function. The first step is to import url_for at the top of your Flask application file.

from flask import url_for

Once you've done that, we can jump over to your HTML files to start implementing url_for. Let's start with your CSS link. Without url_for, you might link your stylesheet using an explicit path.

<link rel="stylesheet" href="static/stylesheets/custom/index.css">

With url_for, we can replace this with a dynamic path.

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

Note that since we are using double-quotes on the outside, we must use single-quotes on the inside. These can be flipped, but we can't use two sets of double-quotes or two sets of single-quotes.


We can also use url_for to generate links to other pages. For example, we might have a link to our main menu.

<a href="https://www.mywebsite.com/menu">Main Menu</a>

Once again, with url_for, we can replace this with a dynamic path.

<a href="{{ url_for('menu') }}">Main Menu</a>

However, for this to work, we need some additional work in our main Python file. First, we'll have to add the render_template function from Flask.

from flask import render_template

Next, we need to make sure to place menu.html in a folder called templates in the root directory. This is an important part, as this is where Flask will look for the file.


Finally, we'll need a function called menu that routes to the menu page of your website and returns a template to your HTML file using render_template.

app = Flask(__name__)

@app.route("/menu")
def menu():
    return render_template("menu.html")

Note that the 'menu' inside the url_for corresponds to the name of the function, the "/menu" inside the route corresponds to the website URL, and the "menu.html" inside the render_template corresponds to the name of the file inside the templates folder. These do not all need to have the same name.


Once you have all of that written out, you'll have a Flask app that successfully leverages url_for!



Komentarze


bottom of page