adamchainz / django-htmx

Extensions for using Django with htmx.
https://django-htmx.readthedocs.io/
MIT License
1.66k stars 140 forks source link

Feature: Add a "render_htmx" function to eliminate boilerplate `if request.htmx: ...` in every view #445

Closed donparakin closed 3 months ago

donparakin commented 5 months ago

Description

So, here's a feature I'd like to see in django-htmx that'll eliminate a lot of boilerplate code in all my views. I'm opening this issue to discuss and refine the idea before doing any code (as this idea might get shot down). The names I've given to functions, templates, etc are open to refinement too so don't worry about them now.

The boilerplate code is:

if request.htmx:
    template_name = "partial.html"
else:
    template_name = "complete.html"
return render(request, template_name, ...)`

This uses the Django provided render shortcut:

render(request, template_name, context=None, content_type=None, status=None, using=None)

My idea is to have django-htmx provide a render_htmx shortcut:

render_htmx(request, template_dir, context=None, content_type=None, status=None, using=None)

The difference is that instead of a template_name being passed as the 2nd paramter, a template_dir is passed. This is set to the path of a directory within the template family of directories. Expected to be in template_dir are templates with names _page.html and _htmx.html.

render_htmx() will render either template_dir + "/_page.html" or template_dir + "/_htmx.html" depending on the value of request.htmx.

So, the 5 lines of boilerplate code above (in many many of my views) becomes 1 line:

return render_htmx(request, "myapp/mypage", ...)

Note that in many cases _page.html will do the needful to build the outer parts of the full page and then {% include "./_htmx.html" %} to get the inner guts (so identical in full page and htmx partials ; no need to duplicate code).

adamchainz commented 3 months ago

There are a lot of different approaches to using request.htmx and partial rendering of templates. For example, django-template-partials provides an alternative that to be documented in #413. Because of this, I think it’s better that you implement any such short “helper” in your project, rather than django-htmx provide anything.