【问题标题】:Context variables on several templates多个模板上的上下文变量
【发布时间】:2021-10-20 17:52:38
【问题描述】:

我有一个 view,它返回上下文 {}。我不需要在一个template.html 中使用这些上下文变量,而是在几个模板中使用。 我该怎么做?

return render(request, 'cart/cart_detail.html', {
                                           'order':order,
                                           'order_item':order_item,
                                           'total':total}

【问题讨论】:

  • 你愿意使用基于类的视图吗?还是只是基于函数的视图?
  • @Jarad 只是功能视图

标签: django django-views django-templates


【解决方案1】:

我猜你可以使用上下文处理器,这就是我用来在导航栏中获取上下文文本的方法,然后在我的所有模板中显示它:

1 - 在您的应用中创建一个 context_processors.py,然后在其中添加您的函数。

2 - 在 settings.py 中

        TEMPLATES = [
        {
        ...
            'OPTIONS': {
                'context_processors': [
                    ....
                    'your_app_name.context_processors.your_function_name',
                ],
            },
        },
    ]

3 - 在您的模板中使用它:

    def your_function(request):
        // ... whatever you have or nothing
        return dict(order=order,order_item=order_item,total=total)

(我可能忘记了一些东西,您可以查看文档),希望对您有所帮助

【讨论】:

  • 谢谢!明天我将尝试您的选择,如果可行,我会将其标记为解决方案。问题:context_processors.py 只创建一个文件或一个包?
猜你喜欢
  • 2018-09-26
  • 1970-01-01
  • 2017-01-29
  • 2013-09-18
  • 1970-01-01
  • 2012-01-30
  • 2023-03-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多