Skip to content

Instantly share code, notes, and snippets.

@eyecatchup
Last active September 8, 2017 15:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eyecatchup/fd51f6d4d08ce943495075cc88226c50 to your computer and use it in GitHub Desktop.
Save eyecatchup/fd51f6d4d08ce943495075cc88226c50 to your computer and use it in GitHub Desktop.

ES6 Template Strings 101

Using inline Javascript:
const dog = {
    name: 'Snickers', 
    age: 2 
};

const markup = `<p>${dog.name} is ${dog.age * 7}</p>`;

console.log(markup);
//  <p>Snickers is 14</p>
Nesting template strings:
const dogs = [
    { name: 'Snickers', age: 2 },
    { name: 'Hugo', age: 8 },
    { name: 'Sunny', age: 1 }
];

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

console.log(markup);
//  <ul><li>Snickers is 14</li><li>Hugo is 56</li><li>Sunny is 7</li></ul>
Intending to create prettier output strings:
// note the use of join value to keep indention accross nested items
const prettyMarkup = `
<ul>
    ${dogs.map(dog => 
        `<li>${dog.name} is ${dog.age * 7}</li>`).join(`
    `)}
</ul>
`;

console.log(prettyMarkup);
//  <ul>
//      <li>Snickers is 14</li>
//      <li>Hugo is 56</li>
//      <li>Sunny is 7</li>
//  </ul>
Using ternary operator for conditional statements:
const prettyMarkupWithCondition = `
<ul>
    ${dogs.map(dog => 
        `<li>${dog.name} is ${dog.age > 6 ? '<em>>old</em>' : `${dog.age * 7}`}</li>`).join(`
    `)}
</ul>
`;

console.log(prettyMarkupWithCondition);
//  <ul>
//      <li>Snickers is 14</li>
//      <li>Hugo is <em>old</en></li>
//      <li>Sunny is 7</li>
//  </ul>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment