dom-template-strings
Create DOM Nodes or Fragments using ES2015 Template Strings.
A fork of domify-template-strings.
Installation
npm install --save dom-template-strings
Usage
New in version 2
The standalone version exports itself as Document.prototype.dom
, so one can do:
It is a breaking change from version 1 which used to export a global dom
function.
using require
The exported module function is bound to the current document:
const dom = const loginBtn = dom `<button>login</button>`loginBtn { } documentbody
The interpolated values the dom
function handles are
- DOM
Node
objects, which will be inserted at the corresponding slot in the DOM tree. - Arrays, which will be handled recursively.
- null or undefined values are converted to empty string (as of version 1.1.0)
All other values will be passed like in usual template strings.
Example with arrays
const dom = const items = 'One' 'Two' 'Three' const list = dom `<ul></ul>` documentbody
Since version 2.2.0 it is also possible to pass instances of
- DocumentFragment
- NodeList
trim whitespace
Since version 2.3.0, if the string literal has whitespace before or after a single node, it is removed. This doesn't happen when there are other characters.
var node = dom` <div>hello</div>`assert
Multiple root nodes
Multiple nodes are returned as a document fragment:
const dom = documentbody
Since version 2.4.0 mapping mapping an array of dom nodes, even of length one, returns a document fragment:
const dom = dom``nodeType == NodeDOCUMENT_FRAGMENT_NODE
Another document
Another document can be used to own the nodes:
const dom = let mydoc = documentlet frag = dom`<p>One</p><p>Two</p><p>One</p>`documentbody
It can also be added to all documents, exactly like the standalone version:
Documentprototypedom = let doc = documentlet frag = docdom`<p>test</p>`// frag.ownerDocument == doc
Compatibility
template tag support
Everywhere a <template>
tag is native, or polyfillable using
https://github.com/webcomponents/template
or
https://github.com/kapouer/template (as a meantime replacement of the former):
npm install @kapouer/template
.
es2015
Software written with dom-template-strings can be babelified to es5, see for example the one-liners in package.json.
License
MIT, see LICENSE file.