ES6 Template Strings in HTML Template Rendering

An interactive demo showing why template literals improve HTML rendering, how an HTML template becomes dynamic, and where this technique has limits.

1. Concatenation vs. Template Strings

Code:
var data = {
  username: 'zhangxinxu'
};

var oldWay = 'The author of this article is: ' + data.username;
var newWay = `The author of this article is: ${data.username}`;
Result:

Plus-sign concatenation

Template string

2. Multiline HTML Is Easier to Read

Code:
let html = `${data.map(function (obj, index) {
  return `<tr>
    <td><input type="checkbox" value="${obj.id}"></td>
    <td><div class="ell">${obj.title}</div></td>
    <td>${obj.time}</td>
    <td align="right">${obj.comment}</td>
  </tr>`;
}).join('')}`;
Result:
Article Title Publish Time Comments

3. A Template Element Is Still Plain Text

Code:
<template id="plainTemplate">
${data.map(function (obj, index) {
  return `<tr>
    <td>${obj.title}</td>
  </tr>`;
}).join('')}
</template>

console.log(document.querySelector('#plainTemplate').innerHTML);
Result:

4. Converting a String into a Template String

Code:
/**
 * Convert a string to a template string
 * @param  {Object} params Template data
 * @return {String}        String after parsing template-string syntax
 */
String.prototype.interpolate = function (params) {
  const names = Object.keys(params);
  const vals = Object.values(params);

  return new Function(...names, `return \`${this}\`;`)(...vals);
};

let htmlList = document.querySelector('#articleTemplate').innerHTML.interpolate(json);
Result:
Article Title Publish Time Comments

5. Business Code Stays Concise

Code:
// Business logic code
var eleTbody = document.querySelector('#businessTable tbody');
var strTemplate = document.querySelector('#businessTemplate').innerHTML;

fakeFetchArticles().then(res => {
  return res.json();
}).then(json => {
  eleTbody.innerHTML = strTemplate.interpolate(json);
});
Result:
Article Title Publish Time Comments

6. JSON Data Feeds the Template

Code:
{
  "code": 0,
  "msg": "Fetched successfully",
  "data": [{
    "id": "0001",
    "title": "How to Display Text as a CSS Background Image?",
    "time": "October 20, 2020",
    "comment": 7
  }]
}
Result:
Article Title Comments

7. Arrow Functions and Escaped HTML

Code:
// Unescape HTML characters   &lt;  =>  <
function escape2Html(str) {
  var arrEntities = { lt: '<', gt: '>', nbsp: ' ', amp: '&', quot: '"' };
  return str.replace(/&(lt|gt|nbsp|amp|quot);/ig, function (all, t) {
    return arrEntities[t];
  });
}

String.prototype.interpolate = function (params) {
  const names = Object.keys(params);
  const vals = Object.values(params);
  return new Function(...names, `return \`${escape2Html(this)}\`;`)(...vals);
};
Result:
Try both buttons to see why escaped template content matters.
# Article Title Comments

8. Tagged Template Literals

Code:
function mark(strings, value) {
  return strings[0] + '<mark>' + value + '</mark>' + strings[1];
}

let topic = 'template literals';
let html = mark`Tagged ${topic} can customize output.`;
Result: