我正在构建一个博客模板页面,它将包括Post列表上下文对象和类别列表上下文对象。
我在views.py中使用基于类的视图:
class CatListView(ListView):
model = Category
context_object_name = 'categories'
template_name = 'blog/category.html'
class PostListView(ListView):
model = Post
context_object_name = 'post_list'
template_name = 'blog/blog.html'urls.py:
urlpatterns = [
path('', views.PostListView.as_view(), name='blog'),
...
]使用include标记在blog.html中包含类别模板:
{% extends 'base.html'%}
{% block content %}
<main class="main-content">
<div class="container mt-8">
<div class="row">
<div class="col-lg-8">
<h2>Post list</h2>
{% for post in post_list %}
{{ post.title }}
{% endfor %}
</div>
<div class="col-lg-4">
{% include "blog/category.html"%}
</div>
</div>
</div>
</main>
{% endblock %}category.html:
<ul class="mt-8">
{% for cat in categories %}
<li>{{ cat.title }}</li>
{% endfor %}
</ul>我只是可以用基于函数的视图来实现t pass the category context in the post.html template. maybe Im,但是是否可以只使用一个基于类的视图将多个上下文传递到一个模板中呢?
发布于 2022-01-15 08:12:02
若要返回多个上下文变量,始终可以重写以下数据方法:
class PostListView(ListView):
# rest of the code
queryset = Post.objects.all()
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['extra_variable'] = # get extra context
return contexthttps://stackoverflow.com/questions/70719673
复制相似问题