@zimpa/template v0.2.0
@zimpa/template
Install
Install the package by running npm install --save @zimpa/template
.
Usage
This templating technique is inspired by the micro template from John Resig.
The idea is that you create a template
tag somewhere in the DOM. In the template
just use regular HTML. When you want to use a variable that must be injected in the HTML put it between {{
and }}
.
Whenever you want to use loops or conditional statements, put these between {%
and %}
.
A very simple template could look like this.
<template id="avatar-tpl">
<div class="avatar">
{% if (image) { %}
<img src="{{ image }}">
{% } %}
<span>{{ lastName }}, {{ firstName }}</span>
{% if (social_platforms.length > 0 %}
<ul>
{% for (i = 0; i < social_platforms.length ) { %}
<li>{{ social_platforms[i] }}</li>
{% } %}
</ul>
{% } %}
</div>
</template>
The template can now be created with:
const tpl = new Template(document.querySelector('avatar-tpl').innerHTML);
Whenever you want to use the template you can trigger the rendering with:
tpl.render({
image: '/assets/avatar.jpg',
lastName: 'Chase',
firstName: 'Chevy',
social_platforms: ['imdb'],
});
It's very important that all variables that are used in the template are provided to the render method as a key of the object provided.
If you don't want to have it a value assign null
or undefined
to the property. Make sure you check for the value in the template.
This will render the same avatar template without an image.
tpl.render({
image: undefined,
lastName: 'Chase',
firstName: 'Chevy',
social_platforms: ['imdb'],
});