Can you create your own template tag that returns a query? If so, how? - Django

Let me make it very easy for my fellow soans (?).

This is how custom template tags usually work -

Template β†’

{% block content %} blah blah blah {% custom_tag_load %} {% endblock %} 

Custom_tag_load is called and returns a string. What I want to return is a set of queries that I could use like this:>

 {% block content %} blah blah blah {% for x in custom_tag_load %} {{ x.datetime }} {% endfor %} {% endblock %} 

Note. > Basically, I try to avoid passing a request through a view, and I'm not sure that it should be convenient for me to store requests in my global context.

+8
django django-templates
source share
2 answers

You can return everything you like from the tag, including the request. However, you cannot use the tag inside the for tag - you can only use the variable (or the variable that passed through the filter). What you can do is get your tag to put the request in a variable in context and use that variable in a for loop. See the documentation on how to set a variable from a tag - although note that the development version has an easier way to do this.

However, you also do not have to worry about setting the request to the context processor. Do not forget that the queries are lazy, so there will be no database hits if the query is not evaluated or repeated in the template.

+5
source share

A template tag can do whatever you want. From your pseudo code, you can do what you need with the inclusion tag:

 #my_tags.py from django import template from my_app.models import MyModel register = template.Library() @register.inclusion_tag('my_template.html') def my_custom_tag(): things = MyModel.objects.all() return {'things' : things} #my_template.html {% if things %} <ul> {% for thing in things %} <li>{{ thing }}</li> {% empty %} <li>Sorry, no things yet.</li> {% endfor %} </ul> {% endif %} #the_view.html {% load my_tags %} {% my_custom_tag %} 

Alternatively, you can write a special tag that will add the request to the context. Hope this helps you.

+2
source share

All Articles