Django - concatenating multiple HttpResponses for partial templates
I have a web page where I populate elements (in a grid) with HTML. This works nicely using Django's render() and querying using HTMX, as required.
I now have a case where I'd like to populate the innerHtml of the element in the page with multiple partial responses - ie. I have data for query1, query2, etc. and want to concatenate the rendered partial HTML responses for query1, query2, ...
Can this be done on the database side by concatenating HttpResponse objects in any way? It would appear fairly efficient to do so, if possible.
Or should I parse on the client side, send off the request, and concatenate all partial HTML snippets there before stuffing them into my web page element?
Can this be done on the database side by concatenating
HttpResponseobjects
I think you mean server side? Responses aren't generated by the database.
Regardless though, no you can't concatenate responses, a request can only have one response. You can either create different views where each one returns the data you're looking for and then make multiple requests on the frontend. Or, you can return JSON where each key is the data you need.
What you want to do is render intermediate templates.
@login_required
def render_demo(request):
from django.template import Context, engines
from django.template import Template as DjangoTemplate
from docs.typst_escape import TypstTemplateColors
profile = request.user.profile
design, palette = profile.preferred_template_design, profile.preferred_template_palette
colors = TypstTemplateColors(**{
field: getattr(palette, field) if palette else "#FF0000"
for field in TypstTemplateColors.__dataclass_fields__
})
typst_template, typst_context = (design.pdf_render, {
"colors": colors,
"user_profile": profile,
})
rendered_typst = DjangoTemplate(typst_template).render(
Context(typst_context, autoescape=False)
)
pdf_bytes = engines["typst"].from_string(rendered_typst).render({})
resp = HttpResponse(pdf_bytes, content_type="application/pdf")
resp["Content-Disposition"] = f'attachment; filename="demo-render.pdf"'
return resp
This calls two intermediate template engines (DjangoTemplate.render(), to do the first-pass on your typical {% jinja syntax %}. DjangoTemplate returns a string, because that's what an HTML body is usually composed of, and passes that string to typst.from_string().render() -- which doesn't even render a string (it makes a PDF, so its output is bytes).
Then we slap that final-final-render (1).docx energy into the HttpResponse, which adds all the things you need to actually send data over the wire. Building the response is always the last thing you do, and you never do it more than once.