Created
June 30, 2023 09:33
-
-
Save danjac/4ad1b5b9348b22a663693764d0c02ccd to your computer and use it in GitHub Desktop.
Django helper function to render one or more template blocks with HTMX
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.http import HttpRequest, HttpResponse | |
from django.template.response import TemplateResponse | |
from render_block import render_block_to_string | |
def render_template_fragments( | |
request: HttpRequest, | |
template_name: str, | |
context: dict | None = None, | |
*, | |
target: str | None = None, | |
use_blocks: list[str] | None = None, | |
**response_kwargs, | |
) -> HttpResponse: | |
"""Renders template blocks instead of whole template for an HTMX request. | |
If not an HTMX request (HX-Request is not `true`) will render the entire template in a `TemplateResponse`. | |
If `target` is provided, will also try to match the HX-Target header. | |
A list of the blocks rendered is added to template context as `use_blocks`. | |
""" | |
if ( | |
request.htmx | |
and use_blocks | |
and (target is None or target == request.htmx.target) | |
): | |
context = (context or {}) | {"use_blocks": use_blocks} | |
return HttpResponse( | |
[ | |
render_block_to_string( | |
template_name, | |
block, | |
context, | |
request=request, | |
) | |
for block in use_blocks | |
], | |
**response_kwargs, | |
) | |
return TemplateResponse(request, template_name, context, **response_kwargs) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment