Context processor in FastAPI

Viewed 472

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)?

2 Answers

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) }}

I don't have experience with Django, but I guess you could create a base template and re-use it in your pages. Example:

base.html

<!DOCTYPE html>
<html lang="en">
<head>
    {% block head %}
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}{% endblock %} - My Webpage</title>
    {% endblock %}
</head>
<body>
    <div id="content">
        <div id="cart">Put your cart logic in here</div>
        {% block content %}{% endblock %}
    </div>
    <div id="footer">
        {% block footer %}
        &copy; Copyright 2021 by <a href="http://domain.invalid/">you</a>.
        {% endblock %}
    </div>
</body>
</html>

somepage.html

{% block title %}Index{% endblock %}
{% block head %}
    {{ super() }}
    <style type="text/css">
        .important { color: #336699; }
    </style>
{% endblock %}
{% block content %}
    <h1>Index</h1>
    <p class="important">
      Welcome to my awesome homepage.
    </p>
{% endblock %}

All these examples and more can be found in the official documentation.

Related