Templates
The current page still doesn’t have a translation for this language.
But you can help translating it: Contributing.
You can use any template engine you want with FastAPI.
A common choice is Jinja2, the same one used by Flask and other tools.
There are utilities to configure it easily that you can use directly in your FastAPI application (provided by Starlette).
Install jinja2
:
- Create a
templates
object that you can re-use later. - Declare a
Request
parameter in the path operation that will return a template.
Note
Notice that you have to pass the request
as part of the key-value pairs in the context for Jinja2. So, you also have to declare it in your path operation.
Tip
By declaring response_class=HTMLResponse
the docs UI will be able to know that the response will be HTML.
Technical Details
You could also use from starlette.templating import Jinja2Templates
.
Then you can write a template at with:
It will show the id
taken from the “context” dict
you passed:
And you can also use url_for()
inside of the template, and use it, for example, with the StaticFiles
you mounted.
In this example, it would link to a CSS file at static/styles.css
with:
And because you are using StaticFiles
, that CSS file would be served automatically by your FastAPI application at the URL /static/styles.css
.
For more details, including how to test templates, check Starlette’s docs on templates.