6

Let's say I have a django site, and a base template for all pages with a footer that I want to display a list of the top 5 products on my site. How would I go about sending that list to the base template to render? Does every view need to send that data to the render_to_response? Should I use a template_tag? How would you do it?

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
rmontgomery429
  • 14,660
  • 17
  • 61
  • 66
  • Although I already answered, the question was asked before: http://stackoverflow.com/questions/1030249/defining-global-variable-in-django-templates , http://stackoverflow.com/questions/2223429/django-global-template-variables – Felix Kling Feb 14 '10 at 23:43

1 Answers1

13

You should use a custom context processor. With this you can set a variable e.g. top_products that will be available in all your templates.

E.g.

# 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

In your settings.py:

TEMPLATE_CONTEXT_PROCESSORS = (
    # maybe other here
    'app.context_processors.top_products',
)

And in your template:

{% for product in top_products %}
    ...
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • I'll give that a try. It sounds just like what I was looking for. – rmontgomery429 Feb 15 '10 at 01:10
  • 1
    Just a remainder. Process of adding context processor is changed in later version of Django. OP's quest can be satisfied according to this question's accepted answer also - https://stackoverflow.com/questions/34902707/how-can-i-pass-data-to-django-layouts-like-base-html-without-having-to-provi – ni8mr Oct 14 '17 at 03:41