aderaaij
11/12/2017 - 3:37 PM

ES6 - Tagged template

With tagged templates we can modify a template string with a function tagged in front of it. str += ${string} <span class='hl'>${values[i] || ''}</span>;

/* The highlight function we tagged on to our template string
Arguments: An array of strings in between variables and the variables
We could use `strings, age, name` as arguments but using the spread operator
to get all the variables is better scalable. */
function highlight(strings, ...values) {
    let str = '';
    /* For each string we add both string and value to the let value. If value doesn't exist, 
    add empty string. */
    strings.forEach((string, i) => {
      str += `${string} <span class='hl'>${values[i] || ''}</span>`;
    });
    
    return str;
}

const name = 'Snickers';
const age = 100;
const gender = 'male'
// Tag the 'highlight' function to the template string, the template string 
// acts as arguments for the function
const sentence = highlight`My dog's name is ${name} and he is ${age} years old and he's a ${gender}`;

document.body.innerHTML = sentence;

console.log(sentence);