1

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> 
New contributor
Comic Hell is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.

1 Answer 1

3

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.

New contributor
Amit Rathiesh is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.