Exploring HTMX, messages and template partials

Today I was adding a cache busting button to a simple custom admin page I had created and I wanted to leverage the Django messages framework to show whether the cache busting had worked. The page was already using HTMX to load a table depending on a dropdown selection so I thought HTMX's Out Of Band swap would be perfect here.

At this point I knew I was going to returning multiple partial templates in a single response so low and below before I knew it I was installing Carlton's template-partials package to make this easier!

Once I got my head around how it works I was able to setup the following template code to render messages sent in a HTMX partial response (note this is extending an admin template).

{% partialdef messages %}
	{% if messages %}
	<ul hx-swap-oob="outerHTML:.messagelist" class="messagelist">
		{% for message in messages %}
		<li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message.message|capfirst }}</li>
		{% endfor %}
	</ul>
	{% endif %}
{% endpartialdef %}

{% block messages %}
	<ul class="messagelist">
	{% partial messages %}
	</ul>
{% endblock messages %}

Along with the following python in the view (although this could easily be a middleware to apply across every request):

def my_view(request)
    messages.success(request, 'Cache Busted!')
    existing_messages = [
        {"message": message.message, "tags": message.tags}
        for message in messages.get_messages(request)
    ]

    response_content += render_to_string(
        f"{template_name}#messages",
        {"messages": existing_messages},
    )

Note that the messages content in the view needs to added after the primary content for the partial template. Also this following HTMX config needs to be set so HTMX knows there are multiple fragments:

htmx.config.useTemplateFragments = true

This would be awesome to be a default for the admin, but that means likely adopting HTMX or replicating the above in JQuery, so seems unlikely. I may see if this can be wrapped into a small package though.