Template Strings

In notebook:
FrontEndMasters Modular Web Development
Created at:
2017-10-01
Updated:
2017-10-02
Tags:
JavaScript Fundamentals

template strings

Part of ES6 (my note: I love it, used it for my site and is very performant).

var n = 5
console.log(`hi
  n=${n}
  wow`)
  • can span multiple lines
  • interpolation with ${...}

This can already replace a lot of templating engines and can be compiled to work on older browsers. (it's pretty well supported)


tagged template strings

This is even more fantastic.

fn`...`

This lets you write your own function that implements how the templating works.

  var n = 5
console.log(tag`hi
  n=${n}
  wow`)

function tag(strings) {
  // it gets string chunks and also handles on the variables
  return arguments // this will do: ↴
  // console.log(tag(['hi\n n=',  '\n wow'], n)
}

You can use this technique for many things, even shaders in gls.

hyperx

He created this library. It's an html parser. It's built to be used a tagged template string function.

  //	****		hyperx.js		****

var hyperx = require('hyperx')
var html = hyperx(function (tagName, props, children) {
  // you pass in your own arguments for what each template should do
  console.log(tagName, props, children)
  // ...
})
var n = 3
console.log(html`<div>
  <h1>${n*1000}</h1>
</div>`)

tagName : e.g. <div> or <html> above props : like attributes (if understood correctly) like className children : If something is not self-closing then the children (stuff between the opening and closing tags)

You can use this to build your own virtualDOM (or DOM diffing algorithm) infrastucture.

$ node hyperx.js

This will print out:

h1 {} [ 3000 ]
div {} ['\n   ', undefined, '\n    ']
undefined