htmx
htmx copied to clipboard
HTMX with Handlebars Client side template does not work with JSON Arrays
I've tried this with HTMX 2.x and 1.x and the current version of Handlebars.
I have the follow data in this format:
{
"items": [
{
"key1": "value1",
"key2": "value2",
"key3": {
"subkey1": "value3",
"subkey2": "value4"
},
"key4": "value4",
"key5": "value5"
},
{
"key1": "value1",
"key2": "value2",
"key3": {
"subkey1": "value3",
"subkey2": "value4"
},
"key4": "value4",
"key5": "value5"
},
{
"key1": "value1",
"key2": "value2",
"key3": {
"subkey1": "value3",
"subkey2": "value4"
},
"key4": "value4",
},
{
"key1": "value1",
"key2": "value2",
"key3": {
"subkey1": "value3",
"subkey2": "value4"
},
"key4": "value4",
"key5": "value5"
}
]
}
The following HTMX does not print out a table with 4 rows. Instead it's a table with only one empty row:
<div hx-ext="client-side-templates">
<div hx-get="/path/to/data"
hx-swap="innerHTML"
hx-target="#data_table"
hx-trigger="load, click, every 600s"
handlebars-array-template="data_template">
<button class="btn btn-primary">Refresh Data</button>
</div>
<template id="data_template">
<table class="table table-striped">
<thead>
<tr>
<th>Address</th>
<th>Client Hostname</th>
<th>Hardware Type</th>
<th>MAC Address</th>
</tr>
</thead>
<tbody>
{{#each items}}
<tr>
<td>{{key1}} </td>
<td>{{key2}} </td>
...
</tr>
{{/with}}
</tbody>
</table>
</template>
<div id="data_table"></div>
If I only have {{items}}, like so:
...
<td>{{items}} </td>
I get this:
[object Object],[object Object],[object Object],[object Object]
Is this a bug or am I missing something?
I got it to work by changing the structure of the source data to match this example: https://github.com/bigskysoftware/htmx/issues/801#issuecomment-1893989978. Also seems like you can't template the full table, but instead need to do tbody only?