I am working on the FastAPI ECommerce website.
I have used Jinja2 as my template engine.
I want to show my shopping cart at the top of each template.
I can do it with context_processor in Django.
In the FastAPI, The code bellow helps us to access string globally in each template:
templates = Jinja2Templates(directory="directory")
templates.env.globals["cart"]="some_string"
But it can only store string while, my cart function needs request as input (see the below code)
cart=Cart(request)
Is there any way to access cart in every FastAPI template (something like context_processor in Django or context_processor decorator in flask)?
Since with fastapi you always have to include the request object as a context in your TemplateResponse (fastapi documentation) you can simply access it inside your template as a variable. For it to work you have to pass the Cart class into the environment globals. I hope the following code helps.
Python Code
templates = Jinja2Templates(directory="directory")
templates.env.globals["cart"] = Cart
Inside the Jinja2 Template
{{ Cart(request) }}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With