【问题标题】:Context processor in FastAPIFastAPI 中的上下文处理器
【发布时间】:2021-09-11 12:10:27
【问题描述】:

我正在开发 FastAPI 电子商务网站。
我使用 Jinja2 作为我的模板引擎。
我想在每个模板的顶部显示我的购物车。
我可以在 Django 中使用 context_processor 来做到这一点。
在 FastAPI 中,下面的代码帮助我们在每个模板中全局访问字符串:

templates = Jinja2Templates(directory="directory")
templates.env.globals["cart"]="some_string"

但它只能存储字符串,而我的购物车功能需要请求作为输入(见下面的代码)

cart=Cart(request)

是否有任何方法可以访问每个 FastAPI 模板中的购物车(类似于 Django 中的 context_processor 或烧瓶中的 context_processor 装饰器)?

【问题讨论】:

  • 嗨@MK-FAST 你是怎么解决的?

标签: python jinja2 fastapi starlette


【解决方案1】:

我没有使用 Django 的经验,但我想您可以创建一个基本模板并在您的页面中重新使用它。示例:

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

所有这些示例以及更多示例都可以在official documentation 中找到。

【讨论】:

  • 感谢您的回复但是我想访问基本模板中的数据。不使用上下文处理器是不可能的。
猜你喜欢
  • 2016-07-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-27
  • 2021-07-09
  • 2020-06-07
  • 2018-02-04
  • 1970-01-01
  • 2023-01-14
相关资源
最近更新 更多