Replies: 4 comments 2 replies
-
If I'm not mistaken, htmx handles this automatically. You just need to make sure that the backend delivers html rather than json. |
Beta Was this translation helpful? Give feedback.
-
I've built a couple of services on htmx 1.6.1 that apply client-side templates to WebSocket messages. I haven't tested if anything big changed since that version that would prohibit such a solution. So the essential parts are... <script src="https://unpkg.com/[email protected]"></script>
<script src="https://unpkg.com/[email protected]/dist/ext/client-side-templates.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.7.7/handlebars.min.js" ...></script> <script id="table-template" type="text/x-handlebars-template">
...
</script> <body hx-ext="client-side-templates">
<div class="block" id="websocket-block" hx-ws="connect:ws" handlebars-template="table-template">
...
</div>
</body> var templates = ["table-template"];
for (let template_name of templates) {
var source = document.getElementById(template_name).innerHTML;
var template = Handlebars.compile(source);
Handlebars.registerPartial(template_name, template);
} If you need to change the WebSocket message before it's parsed by htmx and the template engine, you can do something like this (this is what I've done)... <div class="block" id="websocket-block" hx-ws="connect:ws" handlebars-template="table-template" hx-ext="transform-ws-data"> htmx.defineExtension("transform-ws-data", {
transformResponse : function(text, xhr, elt) {
var data = JSON.parse(text);
/* transformation of data goes here */
return JSON.stringify(data);
}
}); You can use that to adjust Let us know if it worked. |
Beta Was this translation helpful? Give feedback.
-
Since version 1.8.5 you could probably use the htmx:wsBeforeMessage event instead of a custom extension transforming the WebSocket message. |
Beta Was this translation helpful? Give feedback.
-
@gbdlin, I've prepared an example code based on current versions of htmx and its extensions. |
Beta Was this translation helpful? Give feedback.
-
Is it possible to use those 2 features together? I have an existing API using websockets for which I need to create a new frontend. The idea is very simple: when a packet comes through the websocket, I need to re-render a specific part of the site again, using freshly provided data.
I'm trying to figure that out but I don't understand how to configure rendering a HTML tag when websocket packet arrives using client side template.
Beta Was this translation helpful? Give feedback.
All reactions