Gary Tate
Gary Tate

Reputation: 11

Python Flask to change text in a HTML file

I'm trying to create a simple program which will replace {{ test }} with 'Hello world' by following a tutorial, however I am stumped and when I open the HTML file - as {{ test }} is shown on the page instead of 'Hello World' which is what should be appearing.

Any help would be appreciated because I am very unsure on what to do to fix this, thanks.

I am unsure if I have even linked the two files, as to my knowledge it was never specified in the video and I have only just noticed that there is no link between the two files.

Python Code:

from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')

def homepage():
    return render_template('index.html', test='hello world')

if __name__ == '__main__':
    homepage()
else:
    print('Please run this file as main, not as module.')

HTML Code:

<!DOCTYPE HTML>
<html>

<head>
</head>

<body>
<p> {{ test }} </p>
</body>

</html>

Upvotes: 0

Views: 5893

Answers (1)

Alex Hall
Alex Hall

Reputation: 36043

Flask is a webserver. You are not meant to call the functions with app.route. Replace the last part with:

if __name__ == '__main__':
    app.run()

and then visit http://127.0.0.1:5000/ in your browser. The template file is not meant to change.

If for some reason you don't want to run a server but you just want to create HTML files, then use Jinja2, the template engine behind Flask.

Upvotes: 1

Related Questions