| published by | Software Crafts |
|---|---|
| in blog | Software Crafts |
| original entry | ModelRenderers, a possible new component to Django... |
Towards the end of last year I was working with form renderers in my startup to provide a consistent interface for forms across the project. I also used template partials to override widgets, delivering consistent rendering all in one file, a nice win. This made me wonder what other common components in a project get rendered to HTML that could benefit from a single, reusable place to avoid repeating myself.
Carlton's Neapolitan package already has this to some degree. There are two template tag types: one for object detail and one for object list. We also have FormRenderers in Django which already cascade from project down to an individual form, so perhaps we could apply the same logic to render models in a dry, configurable way rather than duplicating templates and logic. This made me wonder, could we have a python class whose role is to define how a model get's rendered? Let's be clear, we're not getting into serializers here and the validation or logic that comes with them, it's similar to the separation of Forms and FormRenders.
I'm thinking that this idea allows the rendering of an object of list of objects in a template like so:
{{ object }}
{{ object_list }}
This can be controlled via a class described above:
class MyModelRenderer(ModelRenderer):
list_template = ''
detail_template = ''
form_renderer = MyFormRenderer
The above class controls how a list of objects would be rendered along with a single object and the form renderer to use. The form side opens up the idea of chaining renderers together in order to find the correct template to use. This then links to the idea of having a template snippet for rendering related models. If you have a foreign key or a many-to-many relationship, your renderer could specify how to render itself as a related field. You could chain model renderers together so that, when rendering a related field, it looks up the appropriate snippet instead of rendering the entire detail or the entire list.
This obviously would be an optional API, but a potentially interesting one. It would certainly alter the look of a Django project and of course nothing stops you from rendering by hand. To me this leans into a different approach to having shared components at the template level, pushing towards not repeating yourself where possible.
Does this peak your interest or does this scream of nothing like Django at all? Let me know your thoughts!