DEV Community

Dr. Azad Rasul
Dr. Azad Rasul

Posted on

4- Create templates in Flask

Each template contains HTML which is the standard language of the web. The template files will be stored in the templates directory inside the project folder. Flask uses the Jinja template library to render templates.

Firstly, create a directory for your project templates using cmd:

(venv) mkdir C:\Users\gardi\flask-tutorial\templates
Enter fullscreen mode Exit fullscreen mode

For example, let's create an HTML file and write Hello World of Programming! inside it in blue color:

<html>
    <body>
        <h1 style='color:blue'>Hello World of Programming!</h1>
    </body>
</html>
Enter fullscreen mode Exit fullscreen mode

Now let's create a python script and save it as hello1.py.

At the beginning of the script we have to import Flask and render_template:

from flask import Flask, render_template
Enter fullscreen mode Exit fullscreen mode

Then create app:

app = Flask(__name__)
Enter fullscreen mode Exit fullscreen mode

We define route hello to return hello.html template using render_template:

@app.route("/")
def hello():
        return render_template('hello.html')
Enter fullscreen mode Exit fullscreen mode

Finally, we run the app:

if __name__ == "__main__":
        app.run(debug=True)
Enter fullscreen mode Exit fullscreen mode

Inside cmd run the Python script with command:

python hello1.py
Enter fullscreen mode Exit fullscreen mode

Open your localhost:

http://localhost:5000/

A web page like the following should be opened:

Image description

* If you like the content, please SUBSCRIBE to my channel for the future content

Top comments (0)