3

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

1
  • Hi @MK-FAST how did you solve? Commented Nov 19, 2021 at 0:21

2 Answers 2

2

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) }}
Sign up to request clarification or add additional context in comments.

Comments

0

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.

1 Comment

Thank you for your reply But I want to access data in the base template. It is not possible without using context processor.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.