DEV Community

Prajval Singh
Prajval Singh

Posted on • Edited on

Complete Flask - Part 2: Folder structure and Templating in Flask

In the previous part we looked at how to create a basic hello world web app in Flask.

In this part of the series we are going to look at flask's folder structure and templating.

Folder Structure

Unless you are creating an API in flask to be used by a frontend framework you are definitely going to need one folder: templates

All of the templates / html files will be in templates folder.
And if you are going to use CSS and JS which you certainly will you need static folder.

So basically it looks like this:

project
|
|---static
     |style.css
     |script.js
|
|---templates
      |index.html
|app.py
Enter fullscreen mode Exit fullscreen mode

Templating

Flask uses a special templating language known as Jinja.
Before diving into jinja let's see how to show html files to the user / client:

  • Import render_template function from flask:
from flask import Flask, render_template
Enter fullscreen mode Exit fullscreen mode
  • Create an index.html file in templates folder:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Flask App</title>
</head>
<body>
    <h3>This is html</h3>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode
  • Go to app.py and create a new route (name it whatever you want):
@app.route('/html-route')
Enter fullscreen mode Exit fullscreen mode
  • Create a function and render the template 'index.html':
def htmlRoute():
    return render_template('index.html')
Enter fullscreen mode Exit fullscreen mode

Fire up your terminal and use flask run command to run the server.
Now go to localhost:5000/html-route and you should see the HTML.

Now try playing around with what you have learnt till now, and solve the challenge below:

Create a route named /signup that renders an html template with a form. It does not need to actually work, I only expect you to create a static HTML form with name, email and password fields.

Complete app.py code:

from flask import Flask, render_template

app = Flask(__name__)

# We created the route below in the part 1 of this series
@app.route('/')
def home():
    return "Hello, World!"

@app.route('/html-route')
def htmlRoute():
    return render_template('index.html')
Enter fullscreen mode Exit fullscreen mode

In the next part of this series we will cover the basics of Jinja templating language. See you next time!

Top comments (0)