I am making a web app using Python and have a variable that I want to display on an HTML page. How can I go about doing so? Would using {% VariableName %}
in the HTML page be the right approach to this?
Asked
Active
Viewed 8.3k times
9

jonrsharpe
- 115,751
- 26
- 228
- 437

Ricky92d
- 181
- 1
- 2
- 8
-
Could you be more specific on how you are using python with your web app? Are you using Django? – Robert Pounder Aug 12 '15 at 12:43
-
3you sure your question is not already answered thousands of times and googling for it is of no use? – Marcin Orlowski Aug 12 '15 at 12:44
-
@RobertPounder I am using Flask. Have information on an API saved as a variable and wish to display this on a HTML page – Ricky92d Aug 12 '15 at 12:46
-
That would certainly be the right approach if you were using a templating language that supported it and passing `VariableName` to the template... but are you? Could you give a [mcve]? Why not just try it and see? – jonrsharpe Aug 12 '15 at 12:46
-
`{{variablename}}` Should work. https://stackoverflow.com/questions/14975114/dynamic-html-content-and-python-variables-with-flask – Robert Pounder Aug 12 '15 at 12:50
-
Funny enough, this is the first result in Google for 'flask html use variable' and actually helped me. – Lelo May 07 '18 at 06:08
1 Answers
36
This is very clearly explained in the Flask documentation so I recommend that you read it for a full understanding, but here is a very simple example of rendering template variables.
HTML template file stored in templates/index.html
:
<html>
<body>
<p>Here is my variable: {{ variable }}</p>
</body>
</html>
And the simple Flask app:
from flask import Flask, render_template
app = Flask('testapp')
@app.route('/')
def index():
return render_template('index.html', variable='12345')
if __name__ == '__main__':
app.run()
Run this script and visit http://127.0.0.1:5000/ in your browser. You should see the value of variable
rendered as 12345

mhawke
- 84,695
- 9
- 117
- 138