Gathering object references on request object via middleware

Hello all,

I have a bit of a conceptual question regarding middlewares. In a project I’ll be outputting various little <style> snippets throughout nested templates. Think something like dynamically generated CSS animation classes specific to an ORM object, and it might (needlessly) output the same CSS several times if the same object/template appears several times, which is very likely. I was thinking a custom middleware could be a good solution to collect them all, avoid outputting duplicates, and load them in <head>. Sort of what django-pipeline does, but more granular.

What I have gotten working so far is a set up like this:

  • Template tag to append my custom-CSS-requring objects to a list on request from inside the various templates, e.g. I can just `{% animate item %} where I need the CSS in a template
  • Middleware to access those objects gathered after the request, in the various templates on the request object, e.g. I end up with a request.animations = [<Item 1>, <Item 2>, ...]
  • Code to render one collective CSS output for all of my objects and insert it into the response.content before </head>

My question is: Does this make any sense or am I having it completely backwards? Is there an easier way that comes to mind to “gather” these items and output them collectively in the <head>?

1 Like

You could use forms.Media with object-based CSS snippets.

I have written a post on this a while back: Object-based assets for Django's forms.Media - Matthias Kestenholz

forms.Media already supports dependencies and deduplication, maybe that’s what you’re after?