A subtemplate is a small template file included inside another template. It keeps long HTML pages manageable and lets the same markup appear in several places. Think of it as a function call for HTML: package a fragment once, then compose pages from it with Django’s {% include %} tag. section 3.8.2
The basic form names the template to insert. Use {% include "partials/musician_results.html" %}, for example, to place a results fragment inside a page. An include can also pass context values with with, allowing one fragment to render different values for each use. section 3.8.2 section 12.4
Reusable pagination footer
A pagination subtemplate can show previous and next links only when prev or next has a value. A parent template supplies those values with {% include "pagination.html" with prev=4 next=6 %}. The fragment owns the link markup; each caller supplies its page-specific data. section 3.8.2
Subtemplates also work as independently rendered HTML segments for HTMX. A musician-results fragment is included during the initial page render, but the same fragment is returned alone when an HTMX request arrives. The target element then receives the replacement or appended HTML without rebuilding the surrounding page. section 12.4 section 12.5
Listing 12.9 An HTMX-capable search view
# RiffMates/bands/views.py
...
def search_musicians(request):
search_text = request.GET.get("search_text", "")
search_text = urllib.parse.unquote(search_text)
search_text = search_text.strip()
musicians = []
if search_text:
parts = search_text.split()
q = Q(first_name__istartswith=parts[0]) | \
Q(last_name__istartswith=parts[0])
for part in parts[1:]:
q |= Q(first_name__istartswith=part) | \
Q(last_name__istartswith=part)
musicians = Musician.objects.filter(q)
data = {
"search_text": search_text,
"musicians": musicians,
}
if request.htmx: #1
return render(request, "partials/musician_results.html", data)
return render(request, "search_musicians.html", data)
This view chooses the full search page for a normal request and the reusable results subtemplate for an HTMX request. section 12.4
Click-to-edit room row
A venue page loops through rooms and includes one show-room subtemplate per row. Clicking Edit fetches a form partial into that row. Saving renders the show-room fragment again, while Cancel fetches that same display fragment independently. section 12.5


