DEV Community

Discussion on: Tagged Template Literals in ES6

Collapse
 
thatjoemoore profile image
Joseph Moore • Edited

I love the many possibilities that tagged template literals open up for us. Did you know that they don't have to return a string, but can, in fact, return any type of object? That detail is behind the project that is at the top of my I-want-to-use-it-but-can't-justify-it-right-now list, lit-html. It lets you construct DOM nodes like so:

import {html, render} from 'lit-html';

function talkAboutFood(name, food) {
  const template = html`<p>My name is ${name} and I love eating ${food}, cool right?</p>`;

  render(template, document.body);
}

talkAboutFood("Kelvin", "Rice");

// Some Time Later

talkAboutFood("Kelvin", "Corn");

The html tag function takes in the HTML string and returns a data structure that, when passed to render, will be efficiently rendered into the DOM. Then, when you invoke it a second time, it'll actually re-use the same object, updating the passed values, and efficiently modify the DOM to match.

And that's just one of the cool ways you could use tagged templates. I'm so excited to see what people come up with next! Thanks for writing this intro!

Collapse
 
sarah_chima profile image
Sarah Chima

This is a great example. Thanks for sharing it.