How to create templates using HTML, JSON & Jquery


This is a very simple example of how we can use an HTML template with our JSON results to inject each JSON result into it's own clone of the HTML template.   This can be very useful for any website where you have a variable number of results from a data source that require the same HTML layout.  e.g. blog results.

 

JSON Object

 

This is our JSON (JavaScript Object Notation) object, this could be obtained from a web service or any other source.

 

 var results =  [{boxName:"Dog",boxText:"Lorem Ipsum",boxImage:"https://darrenwelch.co.uk/images/dog.png"},{boxName:"Cat",boxText:"dolor sit amet",boxImage:"https://darrenwelch.co.uk/images/cat.png"},{boxName:"Mouse",boxText:"consectetur",boxImage:"https://darrenwelch.co.uk/images/mouse.png"},{boxName:"Turtle",boxText:"adipiscing elit",boxImage:"https://darrenwelch.co.uk/images/turtle.png"}];

 

 HTML Template

  

We create an HTML template inside script tags.  

 

<script type="text-custom-template">

 

We use this script tag to implement template functionality (Similar to PHP).  Although this is done on the client side using JavaScript

 

The type "text-custom-template" is not a type that the browser recognises.  Therefore it simply ignores it.  This allows us to place any HTML we like inside it without the browser displaying it.

 

<script type="text-custom-template" id="hidden-template">
  <div class="box">
      <h3 id="box-name"></h3>
      <p id="box-text"></p>
      <img id="box-image" />
  </div>
</script>

 

We have created a simple Div with a header, paragraph and image inside. We will use this as our template to inject our JSON objects into.  To accomplish this we will use the JSON functions.

 

  • $.each() - To iterate through the JSON.
  • $.clone() - To clone the HTML that we have specified within the hidden script tag.
  • $.find() - To find the objects within the cloned HTML.
  • $.text() or $.html() - To inject the object values into the cloned HTML.

 

Here is a working example with the code.

 

Comment