Templating with Jinja2

This chapter will cover the basics of Jinja2 templating from the perspective of Flask; we will also learn how to make applications with modular and extensible templates.

In Flask, we can write a complete web application without the need for third-party templating engine. For example, have a look at the following code; this is a standalone, simple Hello World application with a bit of HTML styling included:

from flask import Flask 
app = Flask(__name__) 
 
@app.route('/') 
@app.route('/hello') 
@app.route('/hello/<user>') 
def hello_world(user=None): 
    user = user or 'Shalabh' 
    return ''' 
<html> 
    <head> 
      <title>Flask Framework Cookbook</title> 
 
    </head> 
      <body> 
        <h1>Hello %s!</h1> 
        <p>Welcome to the world of Flask!</p> 
      </body> 
</html>''' % user 
 
if __name__ == '__main__': 
    app.run() 

Is the preceding pattern of application writing feasible in the case of large applications that involve thousands of lines of HTML, JS, and CSS code, though? Obviously not!

Fortunately, templating offers a solution, because it allows us to structure our view code by keeping our templates separate. Flask provides default support for Jinja2, although we can use any templating engine that suits. Furthermore, Jinja2 provides many additional features that make templates very powerful and modular.

In this chapter, we will cover the following recipes:

  • Bootstrapping the recommended layout
  • Implementing block composition and layout inheritance
  • Creating a custom context processor
  • Creating a custom Jinja2 filter
  • Creating a custom macro for forms
  • Advanced date and time formatting