JavaScript Templates - Example
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:
- Write a Mustache template
- Load the Mustache JavaScript library
- Compile the template using Handlebars
- Evaluate the template, passing in the data
- Add the result of the processed template to the page
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:
- The Mustache template is defined in Lines 32-38.
This template iterates through the seasons
array
{{#seasons}}
starts the iteration{{/seasons}}
ends the iteration- Within the loop,
{{.}}
refers to item of the array
Note that the template is marked as display: none;
by CSS. There are other ways to include templates, which we'll discuss a bit later. - Line 11. Load jQuery for Ajax request and DOM manipulations. We're using the jQuery CDN here.
- Line 12. Load Handlebars JS library from the cdnjs.com service.
- Line 15. Here we define the URL we'll get our seasons list from.
- Line 18. Use jQuery to make the Ajax request, and set the callback function to process the data
- Line 20. Get the template source (uses jQuery to select the
#seasonslisttemplate
and get the html
- Line 21. Use Handlebars to compile the template. This makes the template ready to process. Under the hood, the compile step turns our {{ handlebars template }} into JavaScript code.
- Line 22. Evaluate the template, passing in the data. The evaluation will return the markup generated.
- Line 23. Add the results of the template evaluation to the page. Note here we are using jQuery.
See the working examples:
Copyright © David Heitmeyer