Skip to content
thesarfo

Note

URL Building with url_for()

Using Jinja's url_for() to build links to Flask routes, and passing extra keyword parameters through to the view function.

views 0

url building (creating a link in the html that when clicked, sends you to another html page.)

  1. In your index html, create an anchor tag, and for the href, use the Jinja template to build it out. use the curly braces to build the link.

  2. Jinja has a method called url_for() that helps to get this done. This url_for() accepts a parameter in the form of a name of a function in your Flask server.

  3. Assuming there is a function in your flask server called login() that contains the backend for a login page, you can lead your users to the login page from the homepage like below

  4. for example in your index.html, you can have an anchor tag like <a href="{{url_for('login')}}>Login</a>. This is going to create a hyper link based on the parameter it takes, and call that particular route(the function)

  5. When you use the url_for() inside your html, you can pass other keyword parameters after the main positional argument that is the function in your Flask server. For instance, in our above example we pass the parameter <a href="{{url_for('login', num=3)}}>Login</a>.

  6. This will call the login function in your server and pass the num=3 inside the login function as parameters.

So you can catch those parameters inside the app route. This can be done by using the angle brackets with the parameter inside it. eg: @app.route("/Login/<num>").

  1. You will also need to add that num parameter as an input to your Login function. like below
@app.route("/Login/<num>")
def Login(num):
print(num)
return render_template("blog.html")