htmx icon indicating copy to clipboard operation
htmx copied to clipboard

htmx client-side-template does not work with JSON array

Open ieugen opened this issue 3 years ago • 1 comments

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.

ieugen avatar Nov 01 '22 15:11 ieugen

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 }}

ieugen avatar Nov 02 '22 08:11 ieugen

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 avatar Dec 02 '22 16:12 1cg

@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!

camgaertner avatar Aug 22 '23 12:08 camgaertner