htmx
htmx copied to clipboard
htmx client-side-template does not work with JSON array
Hi,
If the server returns an array, then client-side-template can't be used.
https://github.com/bigskysoftware/htmx/blob/master/src/ext/client-side-templates.js
The code to process the data uses it directly, without wrapping it in an object.
var data = JSON.parse(text);
.......
return Mustache.render(template.innerHTML, data);
If the server returns an array then I believe it's not possible to render that.
The fix IMO would be to pass in a map with the parsed JSON under a specific key:
var data = JSON.parse(text);
.......
return Mustache.render(template.innerHTML, {data: data} );
This way, the user can access arrays via {{ data }} name. (using Mustache syntax )
If data is a map, access will be similar: {{ data.field_name }}
Yeah, the client-side extensions are pretty raw. Happy to consider pull requests against them: I don't use client side templating and would love it if someone who is using it take over and improves them.
@1cg Is it possible to re-open this issue if it's not a duplicate?
As an aside, is there a better pattern for returning JSON and transforming it using htmx? I'm working on a site that displays a list of data. For that, it seems wasteful to return the rendered HTML for each json element, which adds up to a lot more data than using a template and rendering it in the client. I tried this extension but ran into the array issue.
Thank you!