Here are some examples with a bit of annotation that I hope are helpful
to you in your JavaScript adventures!
— David
A review of iteration/loops
Iterating over an Array and iterating through keys in an Object are illustrated at:
Creating Content with DOM and innerHTML Examples
Here, we get started by iterating through data structures, and using either DOM methods to create content or using "string" values for our content and using innerHTML to add those to the page.
- fruits0a.html — iterate through a simple array (list) of fruits and create an unordered list using DOM nodes.
- fruits0b.html — iterate through a simple array (list) of fruits and create a string value for our HTML content and then use innerHTML to place in the container on our page.
- fruits0c.html — here our data structure is more complex, and we are using DOM nodes to create our content. I hope the main purpose of this is to convince you that "templates" are worth learning and will make creating content from data easier!
-
fruits1.html – Iterate through data and use
DOM methods to build up content from data structure. Key aspects are:
-
for (let f in fruits) { }to iterate through keys (f) and access values (fruits[f]) -
for (let type of fruits[f]) { }to iterate through array -
DOM methods of
createElement,createTextNode,appendChild,replaceChildren, and our old favoritequerySelector. -
Using CSS to capitalize apples and oranges with
text-transform: capitalize
-
Handlebars Template Examples
These examples use the Handlebars template system, and I am loading the Handlebars library via the cdnjs, a free and open source CDN (content delivery network).
{
"apples" : [
"Granny Smith",
"Macoun",
"Empire",
"Honey Crisp",
"Albemarle Pippin"
],
"oranges" : [
"Naval Orange",
"Tangelo",
"Clementine",
"Valencia Orange"
]
}
-
fruits2.html – Use a
Handlebars
template print out a list of apple types. Key aspects are:
-
Create the template
<template id="fruit-template"> <ul> {{#apples}} <li>{{.}}</li> {{/apples}} </ul> </template> -
In HTML, load Handlebars library from jsdelivr CDN via
scriptelement. Remember that loading Handlebars must come before Javascript that uses Handlebars! -
In JS, get the text of the template via
innerHTML, and then compile withHandlebars.compile(), and then execute the resulting compiled templatedocument.addEventListener("DOMContentLoaded", function(){ let template = document.querySelector("#fruit-template").innerHTML; console.log(template); let compiledTemplate = Handlebars.compile(template); console.log(compiledTemplate); let myContentResult = compiledTemplate(fruits); console.log(myContentResult); let myContentContainer = document.querySelector("#fruit-basket"); console.log(myContentContainer); myContentContainer.innerHTML = myContentResult; });
-
Create the template
-
fruits3.html – Use a
Handlebars
template iterate through all the fruits and their types. Key aspects
are:
-
Create the template. When
each-ing throughfruits,@keyin Handlebars refers to the key andthisis how to access the value of that key. Not the most intuitive, but we'll make improvements in fruits4.html<template id="fruit-template"> {{#each fruits }} <h2>{{@key}}</h2> <ul> {{#this}} <li>{{.}}</li> {{/this}} </ul> {{/each}} </template>
-
Create the template. When
-
fruits4.html – Let's restructure our data a
bit to make it easier to use. We have the same data, but we'll use a
list of fruits, and have a name and a variety for each of the fruits.
Key aspects are:
-
New data structure is:
{ fruits: [ { type: "Apples", varieties: [ "Granny Smith", "Macoun", "Empire", "Honey Crisp", "Albemarle Pippin", ] }, { type: "Oranges", varieties: [ "Naval Orange", "Tangelo", "Clementine", "Valencia Orange" ] } ] } -
And this makes our template a bit more intuitive:
<template id="fruit-template"> {{#fruits}} <h2>{{ type }}</h2> <ul> {{#varieties}} <li>{{.}}</li> {{/varieties}} </ul> {{/fruits}} </template>
-
New data structure is:
Other Template Systems
Let's see how these examples look with other template systems, such as Nunjucks templates.
Nunjucks Template Examples
Nunjucks is another popular JavaScript template system.
{
"apples" : [
"Granny Smith",
"Macoun",
"Empire",
"Honey Crisp",
"Albemarle Pippin"
],
"oranges" : [
"Naval Orange",
"Tangelo",
"Clementine",
"Valencia Orange"
]
}
-
fruits2-njk.html – Use a
Nunjucks template
print out a list of apple types.
The Nunjucks template is in a separate file in
Key aspects are:views/fruits2.njk-
Create the template
<h2>Apples</h2> <ul> {% for variety in apples %} <li>{{ variety }}</li> {% endfor %} </ul> -
In HTML, the Nunjucks library is loaded from jsdelivr CDN via
scriptelement. Remember that loading Nunjucks must come before Javascript that uses Nunjucks! -
The Nunjucks template is not in the HTML, but in a separate file.
Nunjucks is configured with a directory name (in our case
views) and then the template (fruits2.njk) is requested from this directory.document.addEventListener("DOMContentLoaded", function(){ nunjucks.configure('views', { autoescape: true }); /* 'views' is the directory where the nunjucks templates are located */ let myContent = nunjucks.render('fruits2.njk', fruits); console.log(myContent); let fruitContainer = document.querySelector("#fruit-basket"); fruitContainer.innerHTML = myContent; });
-
Create the template
-
fruits3-njk.html – Use a
Nunjucks template
iterate through all the fruits and their types. Key aspects are:
-
In Nunjucks we can iterate through key/values getting both the
value and key int he iteration. In our case,
typeandvarieties. Thevarietiesis an array and can be looped through to make the list of fruit varieties. The Nunjucks templateviews/fruits3.njklooks like:{% for type, varieties in fruits %} <h2>{{ type }}</h2> <ul> {% for variety in varieties %} <li>{{ variety }}</li> {% endfor %} </ul> {% endfor %}
-
In Nunjucks we can iterate through key/values getting both the
value and key int he iteration. In our case,
-
fruits4-njk.html – Let's go to our
restructured data we used earlier.
-
New data structure is:
{ fruits: [ { type: "Apples", varieties: [ "Granny Smith", "Macoun", "Empire", "Honey Crisp", "Albemarle Pippin" ] }, { type: "Oranges", varieties: [ "Naval Orange", "Tangelo", "Clementine", "Valencia Orange" ] } ] } -
And this makes our template:
{% for fruit in fruits %} <h2>{{ fruit.type }}</h2> <ul> {% for variety in fruit.varieties %} <li>{{ variety }}</li> {% endfor %} </ul> {% endfor %}
-
New data structure is:
Liquid Template Examples
Liquid templates are similar in syntax to Nunjucks. Liquid is an open source project that created and used by the Shopify, a popular e-commerce platform.
Below are the same examples as above, but implemented with Liquid templates.