Examples
About 2 min
Examples
Main example
Source
import { compile } from "hmpl-js";
const templateFn = compile(
`<div>
<button class="getHTML">Get HTML!</button>
{
{
"src":"/api/test",
"after":"click:.getHTML",
"repeat":false,
"indicators": [
{
"trigger": "pending",
"content": "<div>Loading...</div>"
}
]
}
}
</div>`
);
const wrapper = document.getElementById("wrapper");
const elementObj = templateFn();
wrapper.appendChild(elementObj.response);
Registration form
Source
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="text" name="login" id="login" required /><br/>
<label for="password">Password: </label>
<input type="password" name="password" id="password" 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);
Working with a table
Product name | Quantity |
---|---|
Coca Cola | 10 |
Lays | 4 |
Source
import { compile } from "hmpl-js";
const templateFn = compile(
`<div>
<table>
<caption>
List of products in the store
</caption>
<thead>
<tr>
<th scope="col">Product name</th>
<th scope="col">Quantity</th>
</tr>
</thead>
<tbody>
<tr>
<td>Coca Cola</td>
<td>10</td>
</tr>
<tr>
<td>Lays</td>
<td>4</td>
</tr>
{
{
"src":"/api/products",
"after":"submit:#form",
"autoBody":true,
"indicators": [
{
"trigger": "pending",
"content": "<tr><td>Loading...</td><td>Loading...</td></tr>"
}
]
}
}
</tbody>
</table>
<form id="form">
<div class="form-example">
<label>Product name: </label>
<input type="text" name="product" id="product" required /><br/>
<label>Quantity: </label>
<input type="number" name="quantity" id="quantity" required />
</div>
<div class="form-example">
<input type="submit" value="Add product" />
</div>
</form>
</div>
`
);
const obj = templateFn({ credentials: "same-origin" });
const wrapper = document.getElementById("wrapper");
wrapper.appendChild(obj.response);