DEV Community

antonmak1
antonmak1

Posted on • Edited on

How to get html from the server using javascript using fetch (hmpl-js module)?

You can use the hmpl-js package to load HTML from the server. It works on fetch, so it can help you avoid writing a bunch of code:

<div id="wrapper"></div>
<script src="https://unpkg.com/hmpl-js"></script>
<script>
const templateFn = hmpl.compile(
  `<div>
    <button class="getHTML">Get HTML!</button>
    <request src="/api/test" after="click:.getHTML"></request>
  </div>`
);

const wrapper = document.getElementById("wrapper");

const elementObj = templateFn({
  credentials: "same-origin",
  get: (prop, value) => {
    if (prop === "response") {
      if (value) {
        wrapper.appendChild(value);
      }
    }
  },
});
</script>
Enter fullscreen mode Exit fullscreen mode

or

import { compile } from "hmpl-js";

const templateFn = compile(
  `<div>
    <button class="getHTML">Get HTML!</button>
    <request src="/api/test" after="click:.getHTML"></request>
  </div>`
);

const wrapper = document.getElementById("wrapper");

const elementObj = templateFn({
  credentials: "same-origin",
  get: (prop, value) => {
    if (prop === "response") {
      if (value) {
        wrapper.appendChild(value);
      }
    }
  },
});
Enter fullscreen mode Exit fullscreen mode

The function will fire dynamically, depending on the update of properties in the object.

Top comments (0)