observablehq / htl

A tagged template literal that allows safe interpolation of values into HTML, following the HTML5 spec
https://observablehq.com/@observablehq/htl
ISC License
305 stars 24 forks source link

No wrapping <div> when there are multiple nodes #9

Closed ariofrio closed 4 years ago

ariofrio commented 4 years ago

htl.html<button>Hey</button> Text returns a DocumentFragment instead of a <div>, which breaks backwards compatibility with stdlib.html and prevents the result from being displayed by default in Observable if import { html } from "@observablehq/htl" is used.

See https://observablehq.com/@ariofrio/htl-html-vs-stdlib-html

mbostock commented 4 years ago

That’s correct, and it’s explicitly covered in the documentation:

https://observablehq.com/@observablehq/htl

If multiple top-level nodes are given, the result is a document fragment. (Observable doesn’t display fragments because it would dissolve them!) If you’d prefer an element, wrap your markup in your element of choice.

That said, I was thinking about this last night, and I think I’d like to change the API as follows:

This way, you can use html if you want the implicit SPAN, but if you need a more accurate interpretation of the specified markup (as when composing multiple pieces of markup), you can opt-in to using html.fragment. And it’ll be more backwards-compatible with the existing Observable standard library, though that’s explicitly not a goal (because the existing html tagged template literal is dangerous).

(There’ll be an svg.fragment too.)

ariofrio commented 4 years ago

Great ideas, and thanks for pointing out that this is documented! I must have missed it the first time around.