bigskysoftware / htmx

</> htmx - high power tools for HTML
https://htmx.org
Other
37.69k stars 1.28k forks source link

Fix Handlebars support in client-side-templates extension #801

Open gkmcd opened 2 years ago

gkmcd commented 2 years ago

Handlebars templates don't seem to work with the client-side-templates extension.

<div hx-ext="client-side-templates">
    <div hx-get="http://localhost:5000/api/topics?include=user"
            hx-target="#target" 
            hx-swap="innerHTML"
            hx-trigger="load"
            handlebars-template="topic-list">
    </div>

    <div id="target"></div>

    <template id="topic-list">
        <p>handlebars template</p>
    </template>

</div>

TypeError: Handlebars.partials[templateName] is not a function

There appears to be a number of steps missing to properly create a handlebars partial. I've modified the handlebars section of the client-side-extensions script to achieve working Handlebars templates:

var handlebarsTemplate = htmx.closest(elt, "[handlebars-template]");
if (handlebarsTemplate) {
    // get json data
    var data = JSON.parse(text);
    // find value of the handlebars-template attribute
    var templateName = handlebarsTemplate.getAttribute('handlebars-template');
    // use this name to find the template element by id
    var templateElement = htmx.find('#' + templateName);
    // make the actual template
    var template = Handlebars.compile(templateElement.innerHTML);
    // register compiled template with Handlebars
    Handlebars.registerPartial(templateName, template);
    // run template on data
    return Handlebars.partials[templateName](data);
}

Caution: I am not a JS dev.

1cg commented 2 years ago

I think it is using an older (or different) version of handlebars. Kinda hard to keep the APIs straight. :expressionless:

tomberek commented 2 years ago

What is next here? Document the correct Handlebars version to use? Merge the above fix?

alex1648factory commented 1 year ago

Ended up with exactly the same issue...

brunoamaral commented 1 year ago

I'm also dealing with this issue. Is there a previous version of handllebars that works with htmx ? Been trying but so far didn't get any output.

RayyanNafees commented 8 months ago

This example works for me


<script src="https://unpkg.com/htmx.org"></script>
<script src="https://unpkg.com/htmx.org/dist/ext/client-side-templates.js"></script>

<script src="https://unpkg.com/handlebars@latest/dist/handlebars.min.js"></script>

<table
      class="container"
      hx-ext="client-side-templates"
      hx-get="https://jsonplaceholder.typicode.com/users?_limit=5"
      hx-swap="innerHTML"
      hx-target="tbody"
      hx-trigger="load"
      handlebars-array-template="foo"
    >
      <thead>
        <th>Name</th>
        <th>Email</th>
      </thead>
      <tbody></tbody>
 </table>
<template id="foo">
  {{#each this}}
  <tr>
    <td>{{name}}</td>
    <td>{{email}}</td>
  </tr>
  {{/each}}
</template>