@elementum/template
is a lightweight and powerful HTML template engine for vanilla WebComponents.
To define and init a new Template
, you need to use the html
template tag:
import { html, render } from '@elementumjs/template';
const template = (list) => html`<div>
<p>My list has ${ list.length } item(s).</p>
</div>`;
It's also possible define nested templates to create more complex elements. It is useful for render lists or conditionals:
- Basic template: Include it into the html representation as other value using the
html
tag.const template = () => html`<p>Random number: ${ html`<b>${ Math.random() }</b>` }</p>`;
- Conditional rendering: Return a template based on a condition:
const userProfile = (user) => html`...`; const loginButton = () => html`...`; const template = (userLogged) => html`<div> ${ user !== undefined ? userProfile(user) : loginButton() } </div>`;
- List of templates
const listTemplate = (list) => html`<ul> ${ list.map(item => html`<li>${ item }</li>` ) } </ul>`;
Following the example...
import { html, render } from '@elementumjs/template';
const listTemplate = (list) => html`<ul>
${ list.map(item => html`<li>${ item }</li>` ) }
</ul>`;
const template = (list) => html`<div>
<p>My list has ${ list.length } item(s).</p>
${ listTemplate(list) }
</div>`;
To render the template into a container HTMLElement
, the data to fill the template is passed as an attribute to the template generator function. The result of that function will be parsed by render
function to check if the template is already rendered and update it or is not rendered yet and inject it.
import { html, render } from '@elementumjs/template';
// const listTemplate = ...;
// const template = ...;
const list = [ "item 1" ];
render(template(list), document.body /* the container to render the template */);
// import { html, render } from "https://cdn.jsdelivr.net/gh/elementumjs/template/dist/template.esm.js";
import { html, render } from '@elementumjs/template';
// Create the templates
const listTemplate = (list) => html`<ul>
${ list.map(item => html`<li>${ item }</li>` ) }
</ul>`;
const template = (list) => html`<div>
<p>My list has ${ list.length } item(s).</p>
${ listTemplate(list) }
</div>`;
// Instance the list and render the template into the container.
const list = [ "item 1" ];
render(template(list), document.body);
// Update the list and re-render the template every second
let loop = setInterval(() => {
list.push(`item ${list.length + 1}`)
render(template(list), document.body);
if (counter == 5) clearInterval(loop);
}, 1000);
Import from jsDelivr CDN:
import { html, render } from "https://cdn.jsdelivr.net/gh/elementumjs/template/dist/template.esm.js";
Install via npm
:
npm install @elementumjs/template
ES Module builds are intended for use with modern bundlers like webpack 2 or rollup. Use it with ES6 JavaScript import
:
import { html, render } from '@elementumjs/template';
Checkout other import methods in dist/README.md
.