03 Template Strings - Gilian/001-ES6-By-Wes GitHub Wiki

Template Strings

These give you the opportunity to mix in variables into your strings.

  1. Basic Example
  2. Looping over
  3. Conditional
  4. Nested elements
  5. Tagging (run through function)

Basic Example

const name = "Tobias";
console.log(`Hallo ${name}! Willkommen!`);
// Output: "Hallo Tobias! Willkommen!

Looping over

// Need an array of objects
const dogs = [
    { name: 'Snickers', age: 2 },
    { name: 'Hugo', age: 8 },
    { name: 'Sunny', age: 1 }
];

// Print out all the dogs
const markup = `
    <ul class="dogs">
      ${dogs.map(dog => `
        <li>
          ${dog.name}
          is
          ${dog.age * 7}
        </li>`).join('')}
    </ul>
`;

Conditional

// Create object
const song = {
    name: 'Dying to live',
    artist: 'Tupac',
    featuring: 'Biggie Smalls'
};

// If a song is featured use a ternary operator
const markup = `
    <div class="song">
      <p>
        ${song.name}${song.artist}
        ${song.featuring ? `(Featuring ${song.featuring})` : ''}
      </p>
    </div>
`;

Nested elements (render function)

const beer = {
    name: 'Belgian Wit',
    brewery: 'Steam Whistle Brewery',
    keywords: ['pale', 'cloudy', 'spiced', 'crisp']
};
// Use the function to render the nested object
function renderKeywords(keywords) {
    return `
      <ul>
        ${keywords.map(keyword => `<li>${keyword}</li>`).join('')}
      </ul>
    `;
}
// Standard way
const markup = `
    <div class="beer">
      <h2>${beer.name}</h2>
      <p class="brewery">${beer.brewery}</p>
      ${renderKeywords(beer.keywords)}
    </div>
`;

Tagging

You basically call a function onto the template strings. You have to parameters with the strings divided by the template values and the values themself.

// ...values converts an unknown number of parameters into an array
function highlight(strings, ...values) {
    let str = '';
    strings.forEach((string, i) => {
      str += `${string} <span contenteditable class="hl">${values[i] || ''}</span>`;
    });
    return str;
}

const name = 'Snickers';
const age = 100;

const sentence = highlight`My dog's name is ${name} and he is ${age} years old`;
document.body.innerHTML = sentence;
⚠️ **GitHub.com Fallback** ⚠️