Adding a Template
00:00 In this section, you will take care of the front end, meaning the code that we’re having in our line seven, which is basically our front end code, should be a bit more advanced.
00:12 So you’ll create templates, you will add some styling, and you will add a bit more modularization to make the project scalable if you want to continue working on it in the future.
00:24 Since you are working on the front end, it’s also a good idea to have the browser open on the site to actually see how your website looks and recognize any unwanted changes.
00:36
Copy the URL of your Flask development server and open up a new browser with this URL. Here in my editor, you now see on the left side the app.py
file that serves the h1
headline that you can see on the right side with the waving emoji.
00:56 So any changes that I’m doing on the return string actually reflects on the right side if I reload the browser there. Okay, now you can get to work. The first thing is that you want to serve a template instead of the string in line seven.
01:12
So create a new folder named templates
inside of the root directory of your projects. And inside templates
create a file named base
.html
.
01:30
Hop over to base.html
and add in some basic HTML code. In VS Code, I can use the Emmet extension for that by typing in an exclamation mark and pressing Tab, but you can also get this base
.html
file from the supporting materials of this course because I won’t go over everything that’s in it right now.
01:51
The overall part is that it’s kind of like the main structure of an HTML document, meaning we have some information in a head
object and we have a body
object.
02:01
That’s where we want to put the content in. For now, I will just go over to app.py
, copy the content of the string, the h1
object, and add it inside of body
and then maybe change the text to Hi!, so you can see a difference to the h1
headline you used before.
02:22
With the base.html
template ready, you can go to app.py
inside of your code()
function, you will call the render_template()
function.
02:32
In order to use it, you need to import it. So in line one, you are not only importing Flask
, but you’re also importing render_template
.
02:44
And then in line seven, instead of returning a string in your code()
function, you are calling the render_template()
function with a template name.
02:54
In this case, it’s base.html
.
02:58
You don’t need to add in the template folder or something like that because when you are using a folder named templates
and add it into your root directory of your project, Flask will by default look into this folder, find the base.html
template, and serve this one.
03:14
So let’s see if that works. Save the app.py
file and reload the browser.
03:21
And now it says Hi!, which means we’re serving the base.html
file, which is a great start. So let’s dig in a little bit deeper.
Become a Member to join the conversation.