如何在Django中向基础模板发送数据?

6 投票
1 回答
2895 浏览
提问于 2025-04-15 19:17

假设我有一个django网站,还有一个所有页面都用的基础模板,这个模板的底部我想显示我网站上前五个产品的列表。我该怎么把这个列表传给基础模板来显示呢?每个视图都需要把这个数据发送给render_to_response吗?我应该使用模板标签吗?你会怎么做呢?

1 个回答

14

你应该使用一个自定义上下文处理器。通过这个,你可以设置一个变量,比如说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 %}
    ...

撰写回答