String identity template tag
Isiah Meadows
isiahmeadows at gmail.com
Mon Dec 10 19:08:54 UTC 2018
It'd be *way* easier to construct simple template tags if there was a
built-in identity tag, like this:
```js
String.identity = (template, ...args) => {
let str = ""
for (let i = 0; i < args.length; i++) {
str += template[i] + String(args[i])
}
return str + template[template.length - 1]
}
```
This would also provide some language consistency in that tag-less
templates are evaluated as if they were tagged with the internal
`String.identity`.
The usefulness of this is for simple utility template tags, like:
- `` debug`Value: ${value}` ``, where `value` is auto-inspected.
- `` trust`html` ``, which returns a raw HTML virtual DOM node.
- `` escape`trusted ${untrusted}` ``, which escapes template variables
Here's how `debug` and `trust` above would be implemented:
```js
// `debug` - logs a message with inspected values to the console
const debug = (template, ...args) =>
String.identity(template, ...args.map(arg => util.inspect(arg)))
// `trust` - returns a Mithril `m.trust` vnode
// https://mithril.js.org/trust.html
const trust = (...args) =>
m.trust(String.identity(...args))
// `escape` - logs a message with inspected values to the console
const escape = (template, ...args) =>
String.identity(template, ...args.map(escapeString))
```
-----
Isiah Meadows
contact at isiahmeadows.com
www.isiahmeadows.com
More information about the es-discuss
mailing list