Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
donparakin opened this issue Jun 5, 2024 · 1 comment

Comments

@donparakin
Copy link

donparakin commented Jun 5, 2024

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
Copy link
Owner

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.

@adamchainz adamchainz closed this as not planned Won't fix, can't repro, duplicate, stale Aug 5, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants