Course Content
Flask Intensive Course: Web Development with Python
Flask Intensive Course: Web Development with Python
Templates Jinja2
Let's jazz up our content using HTML tags, but it's usually better to keep them in a separate file.
Flask knows just where to look for these templates. We're going to create a directory with the same name, so right-click in the root directory and select New Folder. Name it templates. Inside this folder, work your magic by creating a new file named index.html. This is the go-to name for the main page template.
Now, what's a template, you ask? Well, it's like a text file with placeholders for all the dynamic stuff related to a request. When these placeholders get filled with real values, we call it rendering. Flask is pretty nifty because it relies on a powerful template engine called Jinja2 to make all of this happen.
Templates are HTML files that include placeholders for dynamic content. These placeholders are enclosed in double curly braces, like {{ variable_name }}
, and can be filled with data from your Flask application.
index
index
index
Let’s rewrite our function to connect with the template.
render_template
is a function provided by Flask that allows you to render and display an HTML template.
We are closer to a more proficient application.
Now, consider the Template inheritance. We can build a basic template with already defined structure, blocks, and design.
Create a new file in the template directory named base.html.
Just write the !
exclamation mark and click the Tab button, and you will receive standard HTML markup.
Or copy this markup from this example:
The file's name in the example below doesn't correspond to the file's name in our project.
index
index
index
But it is universal, and we don't need to repeat all this code from page to page. We will signify blocks, and Jinga2 will help us.
The file's name in the example below doesn't correspond to the file's name in our project.
index
index
index
Come back to the index.html file and redraft it accordingly to Template inheritance
index
index
index
Now, we have an even more functional site. It is just beginning. Are you as excited as I am?
Thanks for your feedback!