A template engine is used to separate presentation logic from data. Through impressions, filters, conditionals, bucles or imports, it allows you to generate the HTML code necessary to represent a web page. The template engine are widely used in server-side programming, since they allow the presentation of data without having to modify the source code.
In short, with a templating engine it is possible to present the data handled by the server, specifically FastApi, and generate the HTML in the process; for example, if we have a list of users, we can print it in a table or similar in HTML using certain functionalities (directives).
About Jinja
Jinja is a template engine written in Python designed to be simple and expressive; Jinja is the templating engine used in other Python web frameworks, such as Flask, it is also very similar to the one used by Django.
With Jinja as a template engine we can easily render API responses.
Jinja's templating engine uses square brackets { } to distinguish its expressions and syntax from HTML:
- The {{ }} syntax is called a variable block and we can use it to print in the template.
- The {% %} syntax is used to control structures such as if/else, loops, and macros.
- The {# #} syntax is for comments.
Using Jinja in FastAPI
In this section, we will see how to install Jinja 2 in a FastAPI project and different examples of how we can use both technologies together to create a web application that will not only process requests on the server and return a response in JSON format, but also also process requests to return HTML pages as responses with which we can manage data.
Install Jinja
To install the template engine known as Jinja, we execute in the project:
$ pip install Jinja2To use Jinja, we'll create a folder to store the templates:
templates
And a section for homework:
templates\task
And an HTML file:
templates\task\index.html
With the following content:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>FastAPI</title>
</head>
<body>
<h1>Hello world</h1>
</body>
</html>
In the api.py file, we'll create a Jinja2Templates instance object that takes the root folder of the templates as a parameter:
api.py
from fastapi import Request
from fastapi.templating import Jinja2Templates
templates = Jinja2Templates(directory="templates/")
And we create a function that receives as a parameter the location of the template to be rendered and the user's request:
@app.get('/page')
def index(request: Request):
return templates.TemplateResponse('task/index.html',{"request": request})If we access from the browser, we will see:
Hello world