【问题标题】:Django: How to display context data from one template on multiple templatesDjango:如何在多个模板上显示来自一个模板的上下文数据
【发布时间】:2020-08-06 07:38:43
【问题描述】:

我必须在每个视图中使用上下文更新方法,以便显示来自我的 sidebar.html 模板的数据,这些数据我包含在其他模板中作为我的导航的一部分。还有另一种方法可以包含来自我的 sidebar.html 其他模板的数据吗?我将不得不为很多模板执行此操作,而且似乎不是正确的方法。

blog/views.py

class BlogPostDetailView(DetailView):
    model = BlogPost
    context_object_name = "post"
    template_name = "blog/single.html"

    def get_context_data(self, **kwargs):
        context = super(BlogPostDetailView, self).get_context_data(**kwargs)
        context.update(
            {
                "categories": Category.objects.all().annotate(
                    post_count=Count("categories")
                )
            },
        )

        return context

核心/views.py

class HomeView(ListView):
    model = BlogPost
    context_object_name = "posts"
    template_name = "core/index.html"
    paginate_by = 4
    ordering = ["-date_posted"]

    def get_context_data(self, **kwargs):
        context = super(HomeView, self).get_context_data(**kwargs)
        context.update(
            {
                "categories": Category.objects.all().annotate(
                    post_count=Count("categories")
                )
            },
        )

        return context

core/includes/sidebar.html

...
<div class="sidebar-box ftco-animate">
    <h3 class="sidebar-heading">Categories</h3>
    <ul class="categories">
        {% for category in categories %}
        <li><a href="#">{{ category.title }}
                <span>({{ category.post_count }})</span></a></li>
        {% endfor %}
    </ul>
</div>
...

【问题讨论】:

    标签: django django-views django-templates


    【解决方案1】:

    使用 djangos 上下文处理器,您可以在所有模板库中获取该数据,而无需在所有模板中传递上下文

    例如,我想要站点设置,它包括所有该列的联系人和电子邮件地址等站点设置,因此我将为此创建一个上下文处理器

    新建文件

    context_processor.py

    在那

    from foo import Configuration
    
    def code_base(request):
    
        conf = Configuration.objects.all()
        return {'conf':conf}
    
    Note: also add that context processor in the settings.py under templates on the context processor list 
    

    所以从现在开始,您不必在所有模板中传递 'conf' 作为上下文,您可以直接访问 {{ conf }} 而无需在模板中传递上下文

    【讨论】:

      猜你喜欢
      • 2021-04-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-30
      • 2021-10-01
      • 1970-01-01
      • 2020-07-17
      • 2017-05-21
      相关资源
      最近更新 更多