Search
Learn
Share

jQuery: Simple template solution without plugins

Published by Profile Image LGK on 14 June, 2016
269 views
This is a great and simple solution to use HTML templates in your jQuery code.

First create a template area in your HTML document:
<section class="tpl-area">
</section>

To make sure that the template area is not visible add this CSS:
.tpl-area,
.tpl-area * {
display: none !important;
}

Make a template:
<section class="tpl-area">
<article id="tpl-hello">
<h1>Hello, <span class="hello-text"></span>!</h1>
</article>
</section>

Place a container where the output should appear. Of course outside of .tpl-area:
<div id="output"></div>

Use the template in your code:
var names = ["Luna", "Dean", "Dobby"];

// Make sure the output container is empty
$("#output").empty();

for (var i = 0; i < names.length; i++) {
// Clone the template
var element = $("#tpl-hello").clone();

// And fill it
$(element).find(".hello-text").text(names[i]);

// Place this copy
$("#output").append($(element).html());
}

You can find a live demo here:
http://codepen.io/lgkonline/pen/JKXwow