We'll focus on using the Handlebars template library. Other template systems will do similar things though, with different syntax.
With Handlebars, the key parts are:
Handlebars syntax are based on double curly braces, like {{ handlebar expression }}
.
So to iterate through the <code>seasons</code> array, our Handlebars template would look like:
<ul>
{{#seasons}}
<li>{{.}}</li>
{{/seasons}}
</ul>
To re-implement our "seasons list" example using Handlebars, we could something like:
<!DOCTYPE> | |
<html lang="en"> | |
<head> | |
<title>List of Seasons Using jQuery</title> | |
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"> | |
</script> | |
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.7.7/handlebars.min.js" integrity="sha512-RNLkV3d+aLtfcpEyFG8jRbnWHxUqVZozacROI4J2F1sTaDqo1dPQYs01OMi1t1w9Y2FdbSCDSQ2ZVdAC8bzgAg==" crossorigin="anonymous"></script> | |
<style> | |
#seasons_container { | |
border: medium solid green; | |
background-color: #efe; | |
} | |
.handlebars { display: none; } | |
</style> | |
<script> | |
$(document).ready(function() { | |
$.getJSON("seasons.json", | |
function (data) { | |
var mysource = $('#seasons_template').html(); | |
var mytemplate = Handlebars.compile(mysource); | |
var myresult = mytemplate(data) | |
$('#seasons_container').html(myresult); | |
}); | |
}); | |
</script> | |
</head> | |
<body> | |
<h1>Seasons</h1> | |
<div id="seasons_container"> | |
Seasons List goes here. | |
</div> | |
<div id="seasons_template" class="handlebars"> | |
<ul> | |
{{#seasons}} | |
<li>{{.}}</li> | |
{{/seasons}} | |
</ul> | |
</div> | |
</body> | |
</html> |
seasons
array
{{#seasons}}
starts the iteration{{/seasons}}
ends the iteration{{.}}
refers to item of the arraydisplay: none;
by CSS. There are other ways to include templates, which we'll discuss a bit later.#seasonslisttemplate
and get the html
See the working examples:
Copyright © David Heitmeyer