pythonflask

How to pass variables to a template HTML with Flask


i'm currently learning Flask templates, but i can't undestand how to pass a variable to it. Example of my Python code:

from flask import Flask

app = Flask(__name__)

@app.route('/')
def home():
    return {"message":"on"}, 200

@app.route('/user/<string:username>')
def user_profile(username):
    return render_template('profile.html')

My profile.html:

<!DOCTYPE html>
<html>
<head>
    <title>Perfil</title>
</head>
<body>
    <h1>User: (username)</h1>
</body>
</html>

Solution

  • To pass variables from Flask to a template, you need to import render_template and pass keyword arguments when calling it, then use Jinja2 templating syntax to output the value.

    In app.py:

    from flask import Flask, render_template
    
    app = Flask(__name__)
    
    @app.route('/')
    def home():
        return {"message": "on"}, 200
    
    @app.route('/user/<string:username>')
    def user_profile(username):
        return render_template('profile.html', username=username)
    

    And in profile.html:

    <!DOCTYPE html>
    <html>
    <head>
        <title>Perfil</title>
    </head>
    <body>
        <h1>User: {{ username }}</h1>
    </body>
    </html>
    

    The important part is passing username=username to render_template, which makes username available in the template. In the template, use {{ username }} to display the value.