Template Literals - Javascript

Template literals / Template strings are part of ES6 but it is compatible with most of the modern browsers.

Most of the time during web development you will be puting variable values into your HTML dynamically

For example you may be calling some API using ajax to get values of the variables and put them into your HTML

So here we are going to see how to put variable values into your html the old way (ES5) and how to do it using templates (ES6) way.

 

 

ES5

const firstName = 'John';
const lastName = 'Snow';
const city = 'London';
const age = 35;

let html = "<ul>"+
            "<li>First Name: "+firstName+"</li>" +
            "<li>Last Name: "+lastName+"</li>" +
            "<li>City: "+city+"</li>" +
            "<li>Age: "+age+"</li>" +
            "</ul>";

document.body.innerHTML = html;

 As you can see in above code we are directly writing variable values inside html. This is not a nice approach at least after the advent of ES6.

 

Now let's see how we are going to do it in ES6 using template string.

ES6 (template)

const firstName = 'John';
const lastName = 'Snow';
const city = 'London';
const age = 35;

html = `
      <ul>
        <li>First Name: ${firstName}</li>
        <li>Last Name: ${lastName}</li>
        <li>City: ${city}</li>
        <li>Age: ${age}</li>
      </ul>
`;

document.body.innerHTML = html;

As you can see it looks much cleaner , we need to concatenate strings , we are just wrtiting simple html here inside backtick ( ` ), just like we would have done in an html file.

None