Introduction
About 1 min
Introduction
🌐 hmpl is a small template language for displaying UI from server to client. It is based on customizable requests sent to the server via fetch and processed into ready-made HTML. The language is syntactically object-based and integrated with JSON5. Reduce the size of your javascript files and display the same UI as if it was written in a modern framework.
Example 1
HTML before
<div id="wrapper"></div>
<script src="https://unpkg.com/json5/dist/index.js"></script>
<script src="https://unpkg.com/hmpl-js/dist/hmpl.min.js"></script>
<script>
const templateFn = hmpl.compile(
`<div>
{
{
"src":"http://localhost:8000/api/test"
}
}
</div>`
);
const wrapper = document.getElementById("wrapper");
const obj = templateFn();
/**
* obj = {
* response: div,
* status: 200
* }
*/
wrapper.appendChild(obj.response);
</script>
API route - /api/test
<span>123</span>
HTML after
<div id="wrapper">
<div><span>123</span></div>
</div>
Example 2
import { compile } from "hmpl-js";
const templateFn = compile(
`<div>
<form onsubmit="function prevent(e){e.preventDefault();};return prevent(event);" id="form">
<div class="form-example">
<label for="login">Login: </label>
<input type="login" name="login" id="login" required />
</div>
<div class="form-example">
<input type="submit" value="Register!" />
</div>
</form>
<p>
{
{
src: "/api/register",
after: "submit:#form",
repeat: false,
indicators: [
{
trigger: "pending",
content: "<p>Loading...</p>"
}
]
}
}
</p>
</div>`
);
const initFn = (ctx) => {
const event = ctx.request.event;
return {
body: new FormData(event.target, event.submitter),
credentials: "same-origin"
};
};
const obj = templateFn(initFn);
const wrapper = document.getElementById("wrapper");
wrapper.appendChild(obj.response);