代码之家  ›  专栏  ›  技术社区  ›  rmontgomery429

如何将数据发送到Django中的基本模板?

  •  2
  • rmontgomery429  · 技术社区  · 16 年前

    假设我有一个django网站,以及一个包含页脚的所有页面的基本模板,我想显示我网站上前5名产品的列表。如何将该列表发送到要呈现的基本模板?每个视图都需要将数据发送到呈现响应吗?我应该使用模板标记吗?你会怎么做?

    1 回复  |  直到 10 年前
        1
  •  5
  •   Felix Kling    16 年前

    你应该使用 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 %}
        ...