神刀安全网

Streaming template literals

Template literals are pretty cool right?

const areThey = 'Yes'; console.log(`${areThey}, they are`);  // Logs: Yes, they are

You can also assign a function to process the template, known as "tagged" templates :

function strongValues(strings, ...values) {   return strings.reduce((totalStr, str, i) => {     totalStr += str;     if (i in values) totalStr += `<strong>${values[i]}</strong>`;     return totalStr;   }, ''); }  const areThey = 'Yes'; console.log(strongValues`${areThey}, they are`); // Logs: <strong>Yes</strong>, they are

The syntax for tagging a template seems really un-JavaScripty to me, and I haven’t been able to figure out why strings is an array yet each of the values is a separate argument, but meh, it’s a cool feature.

"But how can we involve streams in this?"

…I hear me cry. Well, turns out a tagged template doesn’t have to return a string:

function daftTag() {   return [1, 2, 3]; }  console.log(daftTag`WHY ARE YOU IGNORING ME?`); // Logs: [1, 2, 3]

…and that’s where streams come in.

Generating streams in a service worker allows you to serve a mixture of cached & network content in a single response. This is amazing for performance, but manually combining the streams feels a bit, well, manual. Using template strings is much nicer!

View demo Note: You’ll need Chrome Canary with chrome://flags/#enable-experimental-web-platform-features enabled.

This means we can write templates like:

const metaData = fetch('/metadata').then(r => r.json()); const foo = metaData.then(data => data.foo); const bar = metaData.then(data => data.bar); const whatever = fetch('/whatever').then(r => r.body);  const stream = templateStream`   <h1>${foo}</h1>   <div>${bar}</div>   ${whatever} `;

…and the stream will provide as much content as it can, when it can. So the stream will provide the <h1> opening tag immediately, then wait on the content for foo . whatever is a promise that resolves with a stream, which can be piped so content can be provided as it downloads. The implementation of templateStream is pretty light too, making it a cheap and easy way of building streams from multiple sources.

If you’re wanting something with a few more features (eg conditionals & iteration), DustJS is the only template engine I’m aware of that supports this, but I’m not a fan of the syntax. Hopefully we’ll see other template engines such as handlebars adopt a similar model, although it’s not something they’re interested in right now .

转载本站任何文章请注明:转载至神刀安全网,谢谢神刀安全网 » Streaming template literals

分享到:更多 ()

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
分享按钮