【问题标题】:How can I send data to a base template in Django?如何将数据发送到 Django 中的基本模板?
【发布时间】:2011-01-16 19:43:44
【问题描述】:
假设我有一个 django 网站,以及一个包含页脚的所有页面的基本模板,我想在我的网站上显示前 5 种产品的列表。我将如何将该列表发送到基本模板进行渲染?是否每个视图都需要将该数据发送到 render_to_response?我应该使用 template_tag 吗?你会怎么做?
【问题讨论】:
标签:
python
django
django-templates
【解决方案1】:
您应该使用custom context processor。有了这个,你可以设置一个变量,例如top_products 将在您的所有模板中可用。
例如
# in project/app/context_processors.py
from app.models import Product
def top_products(request):
return {'top_products': Products.objects.all()} # of course some filter here
在你的settings.py:
TEMPLATE_CONTEXT_PROCESSORS = (
# maybe other here
'app.context_processors.top_products',
)
在你的模板中:
{% for product in top_products %}
...