Chapter 4 - Templates and assets files (CSS and Javascript)

Creating Web templates, adding assets to the application, and prettify the application using Bootstrap.

I- Templates

A- Quick introduction to Jinja templates

A template is a file that can be used as a basis to generate files such as configuration files or source code files.

Flask uses Jinja2 as a template engine. The following code illustrates how to generate an HTML file (similar to what we did in chapter2) thanks to Jinja2:

Jinja2 proposes two mechanisms to help developers to generate documents:

  • Expressions
  • Statements
    • If

    • For

B- Using templates

Create a templates folder: it will contain all the templates of the application. Copy the template from Section I-A in templates.

Let's now generate a view that will use this template. To do so, replace the generate_form function (from chapter 2) by the following code:

II- Adding assets to the application

Assets files are files that are used by the browser in addition to the HTML code that is interpreted by a web browser. They can be images, CSS stylesheets or Javascript files.

In Flask, they are stored in the static folder. Create a static folder in your project, and then add three folders in the static folder:

  • css
  • js
  • img

We will add a first asset to the web application: create a theme.css file in the static and fill it with the following code:

Then, in the templates/form.html template, add the line in the HTML header:

III- Using the Bootstrap CSS framework

Bootstrap is a convenient CSS framework that proposes some CSS styling, which enables an easier development of nice a web site.

To use Bootstrap, you have to add a css file and js file to the existing project.

Now modify the HTML template to make it look like this:

The application should be close to what is depicted in the following screenshot: