4 ms·
We are using Django+HTMX for internal applications. Some random tips: - Write a "Django context processor" to inspect requests for "Hx-Request" header, and se
by pphysch 4y ago
We are using Django+HTMX for internal applications.
Some random tips:
- Write a "Django context processor" to inspect requests for "Hx-Request" header, and set a "base_template" variable accordingly. This means that any template that {% extends base_template %} will react to being a full page or just a fragment and you don't even have to think about that in your view logic. Great for progressive enhancement.
- You can get reactive JS elements (for example, a d3.js viz that updates when new data comes in) in a few lines of inline JS by using MutationObserver, and "abusing" HTMX by using views that return JSON targeting a <script> element (`json_script` templatetag can also be used here). In summary, you tell your fancy JS element to render or update whenever a particular <script> element is mutated, and all of it is orchestrated by HTMX.
- greenie_beans 4y agodo you have any code examples you'd be able to share that uses the base_template thing?
- pphysch 4y agoSure, Django docs say this about custom context processors: https://docs.djangoproject.com/en/4.1/ref/templates/api/#writing-your-own-context-processors https://docs.djangoproject.com/en/4.1/ref/templates/api/#wri... So in my context_processors.py file, I write something like: def base_template(request): template = "templates/base.html" # full page if "HX-Request" in request.headers: template = "templates/base_ajax.html" # minimal template return {"base_template": template} And then my template just needs to start with `{% extends base_template %}`. Nothing needs to be done in the view (although you could technically override "base_template" there, if you need to).
- 0xblinq 4y agoI’m all in into the sprinkles approach (I’m a big fan of Hotwire and most of the times that’s what I use) but the Django templates are extremely outdated and limited. I don’t miss it at all. They’re really bad. Compare it to Blade (Laravel) or even ERB (Rails) and it’s night and day.
- pphysch 4y agoDjango templating is limited, but it's not necessarily a problem because you should be putting most of the business logic in the view/service/model anyways. After some initial friction, I don't have any issue with how limited they are.