Hyperglue is an awesome templating engine that accepts vanilla html strings or DOM elements as templates. This is nice because you don't have to learn any fancy new languages and you can update templates you've already rendered without recompiling any HTML.
Although the concept behind this library is faithful to the original, the API is not. More about this under Notes.
How
Set textContent
var
hg
=
require
(
'hyperglue2'
);
var el = hg('<div></div>', 'hello');
// or
var el = hg('<div></div>', { _text: 'hello' });
// <div>hello</div>
Make updates
// note: 'el' is a dom element, not a stringhg(el, 'hello world');// <div>hello world</div>
Form element value (attributes only work for inital values)
hg(el, { input: { _value: 23 }}); // add// <div><input value="42"></div> // but display and js will show 23hg(el, { input: { _value: null }}); // remove// <div><input value="42"></div> // but display and js will show ""
Generic properties
hg(el, { input: { _prop: { checked: true }}}); // sets .checked directly on element
So, I really like the original hyperglue library, but!
the ":first" selector confused me
array updates don't work
can't remove attributes
Detailed explanations below:
The ":first" selector
The first thing you're likely to try with hyperglue is probably something along the lines of: hg('<div></div>', 'hello world') which of course doesn't work, because to select outer elements you actually need to use the ":first" selector like so: hg('<div></div>', { ':first': 'hello world' }). Hyperglue2 does away with ":first" and just assumes you are always talking about the outermost element you've selected, this sacrifices attribute manipulation ease in favor of a more obvious way to set inner content:
Updating an existing dom element (instead of generating a new one from a string) is possible with the original hyperglue, but it doesn't work for arrays. Consider:
Some html attributes like "checked" or "selected" can't be set to falsy values, so the only way to disable them is to completely remove the attribute. You can remove attributes with hyperglue2 by setting the attribute data value to null.