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 "Handlebars" template
- Load the "Handlebars" 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 seasons
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 Handlebars template is defined in Lines 49 — 55.
This template iterates through theseasons
array{{#seasons}}
starts the iteration{{/seasons}}
ends the iteration- Within the loop,
{{.}}
refers to item of the array
- The Handlebars template is process in
buildSeasonsContent
- Load the library (line 6)
- Get the template as text (line 32)
- Compile the template (line 34)
- Process the template with the data (line 36)
- Add result to page (line 39)
See the working examples: