Hi 🙂🖐
Welcome to my new post, In this post, I will show you how to use HTML templates in FastAPI. FastAPI provides amazing methods to render templates in easy ways. You can use any template engine you want with FastAPI.
FastAPI supports Jinja2, the same one used by Flask and other tools.
step 1
Install jinja2
pip install jinja2
step 2
Create folders You need to create two folders.
1 - templates
Inside this folder, you will create the HTML files you want to display.
2 - static
This folder is used for static files like CSS and Javascript.
step 3
Inside templates folder create welcome.html
page
<html>
<head>
<title>Welcome</title>
<link href="{{ url_for('static', path='/css/style.css') }}" rel="stylesheet">
</head>
<body>
<div class="user-name">
<h1>Welcome : {{ name }} ;)</h1>
</div>
</body>
</html>
Now we need to make another folder called css inside static folder to add style.css
file 🤗
.user-name {
margin: 100px auto;
width: 60%;
background-color: #673AB7;
padding: 20px;
color: white;
text-align: center;
font-family: monospace;
}
step 4
Create the main.py
file and import the required modules.
from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
from fastapi.staticfiles import StaticFiles
Setting up static folders and template directories
app = FastAPI()
app.mount("/static", StaticFiles(directory="static"), name="static")
templates = Jinja2Templates(directory = 'templates')
Create route called welcome this route will take name and display it into welcome.html
page
@app.get('/welcome/{name}', response_class = HTMLResponse)
def welcome(name : str, request : Request):
return templates.TemplateResponse(
'welcome.html',
{'request': request, 'name': name}
)
Now we are ready to run the app. 😎
uvicorn main:app --reload
result
Now we're done 🤗
Don't forget to like and follow 🙂
Support me on PayPal 🤗
https://www.paypal.com/paypalme/amr396