Django include template tag include multiple context object
Я создаю страницу шаблона блога, которая будет включать контекстный объект списка Post и контекстный объект списка Category.
Я использую представление на основе классов в файле 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 I
м могу сделать это с помощью представления на основе функций, но возможно ли передать несколько контекстов в один шаблон, используя только представление на основе классов?
Для возврата более чем одной контекстной переменной вы всегда можете переопределить метод get_context_data
следующим образом:
class PostListView(ListView):
# rest of the code
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['extra_variable'] = # get extra context
return context