Viet Phan X

Building MVP with Flask Day 2 – Jinja2 Template Basics

👨‍💻 Software Development
1801
Feb 27, 2019

Today, I want to learn Flask templating system basics.

In the past, I was afraid of learning new frameworks. Mostly because reading any documentation related to the said framework gave me a huge headache.

On one such occasion. I was halfway through step by step guide on how to use Flask / Django templating system, while suddenly I got a serious headache.

To relieve the pain, I immediately closed the guide, turned on youtube. And never attempted to learn the templating system again. Until now.

Instead of taking action, I procrastinated. And daydreamed about how my webpage would look like in Flask / Django. That has to stop.

Today, I want to at least lay down the basic infrastructure for my homepage. The homepage is my favorite starting point in every web development project. Not a lot of imagination is required and you always start with some boilerplate code.

Every homepage on the planet shares the same layout structure.

Why?

Because users are so used to well-known design patterns, that when you start experimenting with crazy ideas. You might go viral, but they will never visit your web again.

Users are consumers and consuming content on a page with e.g. randomly moving menus following your cursor is just plain uncomfortable.

Setting up Git Repository

Okay. With a goal in mind, let's first back up our codebase into some Git cloud service.

I totally forgot this step at the beginning. It's usually the first thing you should do after creating your project folder.

I am using a free Gitlab account for backup and free mac Git client GitKraken for committing to Git repository. If you are afraid of using the command line like me, you will find both tools to be really non-developer friendly.

Creating a new repo in GitKraken and syncing with Gitlab still confuses me as there are so many options.

Should I create repo locally and sync to cloud. Create a repo on cloud and clone to local or create repo locally and sync to self-hosted Gitlab?

After a few trials and errors I figured out the necessary steps:

  • In Gitkraken, click on View all repositories

Gitkraken1

  • Choose Init - Local repository
  • Fill the form and click on Create Repository

Gitkraken2

  • On the left sidebar click on REMOTE
  • Choose the URL option
  • Fill in the URL of your project on Gitlab

Gitkraken3

And. It's done.

Jinja2 template system

So far, our page displays a string, that is rendered by Flask view.

What I want to achieve is to create a header. To do that, I need a way to start adding HTML tags.

If this would be an Html5 project, I would just create an index.html file. Which would contain basic HTML web page elements like header, body, and footer.

Luckily, Flask allows us to create and render HTML files. Not only that, it allows us to break down the HTML page into smaller reusable pieces.

And thanks to template system called Jinja2. We can enrich static HTML content with dynamically generated content by using variables, if statements and for loops.

Anyway, how do we add an HTML template to our Flask view? Before I dig into that, I want to refactor the code according to this guide. You will see why.

Move Flask app to __init__.py

Create an app folder inside our project folder like so.

/financia/app/

In the beginning, we had all our files inside our main project folder. This will be a mess further down the road.

What if I want to add 100 images? The folder would then contain more than 100 files. It's better to categorize files into separate folders, that serve their own purpose. The new app folder will contain will, therefore, contain only app-related code.

In the folder, create a __init__.py file.

from flask import Flask

app = Flask(__name__)

from app import routes

This is just a file, that kickstarts our application. And display whatever content we define with our routes.

Creating Flask view routes.py

Next, create a routes.py file inside our app folder. Then cut and paste hello world view into routes.py.

from app import app

@app.route('/')
def index():
    return "Hello, World!”

Again, we just copied a previously defined view, that renders simple string "Hello World". Whenever a user visits our main domain URL. Now rename app.py into financia.py and code below inside.

from app import app

I just abstracted our app into more layers and files. Before I had a single app.py file, that did everything.

Now, I just call financia.app, that calls our app.py, that calls routes, that need to be rendered.

Okay, let's see if refactoring works. Close and start Gunicorn again.

gunicorn financia:app

Yep. it still works.

2019 02 07 18 33 18 Financia.local Works 1 2

Creating Index.html

Since I didn't break anything with refactoring, I can finally create a base index.html page template. I will store all template files inside conveniently named folder called app/templates.

mkdir templates

Next, create index.html file and fill it with basic html layout.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{{ title }} - Financia</title>
</head>
<body>
    <h1>Hello, {{ user.username }}!</h1>
</body>
</html>

Render HTML file in Flask view

Now I need to tell Flask to render index.html page whenever user visits our main url. It can be done by using render_template() function in our Flask view.

from app import app
from flask import render_template
@app.route('/')
def index():
    return render_template('index.html', title='Home')

That's it. Restart Gunicorn and reload our app in Chrome.

Hey You

Yep, works as usual.

Today, I did a proof of concept, that Flask templating system works. I didn't manage to integrate Bootstrap 4 as I intended to do, but I hope I will get it done in the next session.

After that, I can finally focus on designing layout elements with HTML and CSS.

See ya.


You need a

Innovation Advisor

Fresh eyes help generate new perspectives. Book a free call in which we identify hidden opportunities.

15 min call

Get product feedback


If You Like what I do
You can buy me a coffee 👇
Send via PayPalSend with Bitcoin

🤙 Let's connect

Made by Viet Phan © 2018-2024Privacy Policy