Using a Template

With the introduction of Template Literals, creating HTML has become much easier for novice developers, because Template Literals allow the developer to create HTML in JavaScript that looks and feels like writing in an HTML file.

Creating a Template

Using template literals, it is possible to create an HTML template, complete with white space, tabs, and carriage returns.

For example, if we wanted to create an HTML unordered list of animals with a title, we do so with a template literal.

const list = `
<h2>Animals</h2>
<ul>
  <li>cat</li>
  <li>dog</li>
  <li>mouse</li>
</ul>`

Creating a Template with Variables

With the interpolation syntax (${...}), we can create placeholders in place of the text. Then using variables we can recreate the HTML.

const title = 'Animals'
const animal1 = 'cat'
const animal2 = 'dog'
const animal3 = 'mouse'

const list = `
<h2>${title}</h2>
<ul>
  <li>${animal1}</li>
  <li>${animal2}</li>
  <li>${animal3}</li>
</ul>`

Insert the Template

Just with a string, we can insert a template using either innerHTML or insertAdjacentHTML() depending on the situation.

const title = 'Animals'
const animal1 = 'cat'
const animal2 = 'dog'
const animal3 = 'mouse'

const list = `
<h2>${title}</h2>
<ul>
  <li>${animal1}</li>
  <li>${animal2}</li>
  <li>${animal3}</li>
</ul>`

const $list = document.getElementById('list')
$list.innerHTML = list