ES6 Template Literals in Depth

In notebook:
Article Notes
Created at:
2015-10-29
Updated:
2017-11-10
Tags:
JavaScript Fundamentals
ES6 Template Literals in Depth

Tagged Templates

you can pass your template to a function, that will receive your template string split at the variable points.

E.g. if you have a template string: hello ${name}. I am ${emotion}! and you pass it to an ES6 tagged template function it receives this:

fn(['hello ', '. I am', '!'], 'nico', 'confused')

first parameter is an array, the template string split at at the variables, then just all the variable values.

So to reconstruct the same string (hello nico, I am confused) you would need this function:

function normal (template, ...expressions) {

return template.reduce((accumulator, part, i) => {

  return accumulator + expressions[i - 1] + part
  }
}

and run it:

var name = 'nico', emotion = 'confused';

var text = normal`hello ${name}, I am ${emotion}!`;

this we re-assemble the elements

Using arrays inside an ES6 template literal

you can loop through an array in a template literal:

var tags = ['one', 'two', 'three']

and then:

var html = `<ul>
  ${tags.map(function(tag){return `<li>${tag}</li>`).join(`\n  `)}
</ul>`