chevron-up bell reply instagram twitter2 feed3 finder search-25px-p0

Using Jinja2 with Flask

2017-08-27

Jinja2 is a flexible HTML Template along with with Flask, another commonly used Flask template is Mako.

Install Jinja2

Install with PIP

Basic Operation

1. Determine whether a variable is set or not

in the controller class, usually the app.py, you can do:

2. Determine an array is not empty

In your jinja template you can write:

Notice: Jinja2 can make use of python's inner-built data types such as list and dictionary

3. Use a For Loop

4. Use if, else and elif

5. Jinja 2 template inheritance

Template inheritance is a very important feature in jinja2. With such a feature, one html template can be used as a Parent Class in other programming language. Here is one simple example:

base.html

index.html
Now index.html can re-use the basic structure from base.html

The above code shows index.html inherits from base.html and rewrite the body part. jinja2 template is quite similar to class that the child template can ONLY extends from ONE parent template.

6. Macro

Jinja2 macro is used as Components in the view. For example, there is always a need for Navigation Bar while building the view which would be used in more than one page. With macro, Navigation Bar can be created a component.

Navigation_bar.html

Such a navigation bar can be used in other template html.

index.html

And of course, you can pass a variable to macro:

Navigation_bar.html

In index.html,


As discussed above, it is quite obvious, Jinja2template is using the old & traditional way of Backend server generating data and control all the routes, then render to html.

In the future posts, I will add React or VUE.js to jinja2, combine the data drive and auto-refresh to flask.


Reference

http://www.arkilis.me

arkilis

Comments: