ptr
ptr

Reputation: 3384

Adding variables to current context via a template tag

I'd like a template tag that fetches a queryset of objects and makes them available in the context of the current template. From what I can see this is possible with a simple_tag like so:

@register.simple_tag(takes_context=True)
def get_myobject_queryset(context, string_arg)
    myobjects = MyObject.objects.all()
    context['myobjects'] = myobjects
    return ''

Are there any drawbacks with this method, or is there typically a better way to achieve what I want? I ask only because this feels slightly like a workaround to something I thought would be quite a commonplace task.

Upvotes: 2

Views: 175

Answers (2)

Alasdair
Alasdair

Reputation: 308839

You tag is fine, but you could use the assignment_tag decorator instead.

Upvotes: 1

Alex Parakhnevich
Alex Parakhnevich

Reputation: 5172

Consider writing a context processor.

#myapp/contexts.py
def get_myobject_queryset(request):
    myobjects = MyObject.objects.all()
    return {'myobjects': myobjects}

Don't forget to add a processor to your TEMPLATE_CONTEXT_PROCESSORS settings.

#settings.py
TEMPLATE_CONTEXT_PROCESSORS = (
"django.core.context_processors.request",
"myapp.contexts.get_myobject_queryset",)

Then in template you'll be able to access your variable like {{ myobjects }}

Docs: https://docs.djangoproject.com/en/dev/ref/templates/api/#writing-your-own-context-processors

Upvotes: 2

Related Questions