Hello! I'm Dew Plucky. This is my 3rd Flask tutorial. If you haven't read my previous Flask tutorials click here to see my home page.
In the second tutorial, we learned about routes and displaying HTML files and HTML tags.
Now we will learn about using HTML Layouts and static files in Flask.
Layouts
Assume that you have created multiple HTML files in your app, and these HTML files have lots of common content. In this situation, instead of typing the same content into different HTML files, you can simply create an HTML layout that contains the common content, and use this layout in your other HTML files.
Let's learn how to create an HTML layout. Create an HTML file in the templates folder and call it layout.html
, and create the basic HTML tags in this file.
Next, we will define the parts of the layout that we want to customize in other HTML files. To do this we will use this syntax: {%block ....%}{%endblock%}
I want to customize the title and the body in my index.html file. Let's see how we can do that :
layout.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>{%block title%}{%endblock%}</title>
</head>
<body>
{%block body%}
{%endblock%}
</body>
</html>
index.html
{%extends "layout.html" %}
{%block title%}This is the title{%endblock%}
{%block body%}
Hey! This is the body!
{%endblock%}
Now we can run the app, and see the index page:
We successfully customized the title and the body!
Static Files
Statics are the assets used by your templates: CSS files, JS files, image files, etc. To store your static files, you need to create a folder called static in which you can put these files.
CSS Files
Let's create our static folder, and create a CSS file, style.css, in it.
style.css
body
{
font-size: 50px;
color: gray;
font-family: sans-serif;
}
To use the style.css file for the index.html file, we will add this tag to the index.html file.
<link rel="stylesheet" type="text/css" href="/static/style.css">
Then we can run the app and see the result:
As you can see, the style.css file works.
Image Files
We can do the same thing with image files. I want to display an image on my index.html file. Let's put the image into the static folder:
Then we can create an image tag in the index.html file to display the image.
index.html
Because the image I use was very large, I changed its height.
Now, let's run the app: