Templating in JavaScript, from Zero Dependencies on Up (2021)
blog.jim-nielsen.com
blog.jim-nielsen.com
Years back I dove completely in on Svelte and even wrote my own SSG that helped kick off the Islands/partial hydration crazy... Elder.js. It was fun, but burnt me out of open source.
Today, I only pull for a template language and deal with SSR/Hydration for pages that really need it.
I want JS projects that don't break 6 months after the last build. The way you get that is by not adding more dependencies and not chasing the latest craze.
I was somewhat recently trying to get a 3 year old JS project working. I felt like I was alone in an Egyptian pyramid wondering if I had missed the funeral.
I've settled on ``document.createElement()``: it's a bit rough visually, but that's pretty much the only downside (I've found the time gained with templates to be negligible in front of the overall development time).
A big bonus of dealing with genuine objects is that there's room to extend them to e.g. store additional state/data/handlers/etc., which might otherwise be cumbersome to be set via attributes & cie.
let p = document.createElement("span");
let b = document.createElement("button");
b.innerText = btnText;
if (btnClass) b.classList.add(btnClass);
let m = document.createElement("span");
m.style.display = "none";
m.classList.add(modalClass);
let q = document.createElement("span");
q.classList.add(modalContentClass);
let c = document.createElement("button");
c.innerText = "×";
c.classList.add(modalBtnCloseClass);
// r is an "external" HTMLElement
r.classList.add(modalContentClass);
q.append(c, r);
m.appendChild(q);
p.append(b, m);
It's not that different from writing the HTML (with or without a template). But IMO the great thing here is that, at the end of that chunk of code, you've got pointers to every node of interest. You can then register handlers, target arbitrary nodes in such handlers, without having to navigate through the HTML (e.g. by setting ``id`` or other attributes to help identify them, or by relying on a static HTML structure).And as the parent points, this should prevent some amount of unexpected HTML injection.
There's still a separation between the view and the page structure.
How so?
The "imperative logic" of the previous example is parametrized by a few node pointers. Assuming I understand your approach correctly, your separate imperative logic would still need to be parametrized by some node pointers as well.
Except because you wouldn't have direct access to them, you'd need to use class names or IDs to retrieve them. Hence you would need an extra layer to join the two parts that you've separated, which in my opinion is more mental overhead: the management of those attribute comes at a cost (e.g. naming conflict, more class names to remember, confusion between class names).
Perhaps a more concrete example (bits of code) of your approach might help make your point clearer.
(There are ways to achieve that more declaratively than by building the entire DOM imperatively, JSX and React’s refs is one approach, but I wonder why you assume direct access is always needed in the first place.)
I haven't made a case for it to be a requirement, but rather for direct access to be 1) trivial to achieve 2) more convenient than all of the (Vanilla JS) alternatives that I know of (attributes-based solutions).
> JSX and React’s refs
From a quick glance, I'm not sure this brings anything more than keeping a handful of node pointers around. But it should, at least in some ways, be better that attribute-based solutions.
I'd encourage you to toy with a concrete example, in case you (or I) are missing a subtle point; the previous piece of code is the "view" for a modal "component" which hosts an external HTMLElement (r). See how you'd implement it with both approaches.
With both, the "view" and the logic are still separated. The view is merely encoded differently.
Not really. With declarative approach you can just give HTML to the browser (or some templater) and get your page completely laid out without having any access to any nodes.
In fact, declarative approach does also allow to connect handlers with ease (onclick and similar attributes are very much a thing).
Using onclick handlers doesn’t scale well if we are talking about Web apps with complex GUIs, but then the naive imperative approach of createElement scales potentially even worse. The approaches that do scale tend to favour declarative approach with isolated imperative logic (such as in event handlers).
Yup, but it's more limited: consider the modal: you can't — without relying on attributes, or worse, the page's structure — hide the modal when clicking on the little cross, in an onclick attribute.
> The approaches that do scale tend to favour declarative approach with isolated imperative logic
I think it's key regardless of the approach: you want to break down your pages in pieces (e.g. "components"), have them eventually communicate with each others, while keeping those communications as local as possible.
Very much in the same way we design programs over small units (procedure, function, object, etc.).
It goes without saying...
> At the same time, implementing a full-blown app imperatively directly with createElement would result in an unmaintainable mess
I disagree, and I've built non-trivial UIs with createElement; a key is to have the discipline to keep the "components" well-isolated.
Also Honojs (hono.dev) has a built in HTML function which is quite good and I've used extensively.
I noticed the article doesn't mention escaping HTML, which you probably should do if you're expecting user input. Fortunately, such a utility is included in Deno's standard library: https://jsr.io/@std/html/doc/~/escape
Similarly, for XSS, the `xss` package on npm works great for Deno.
For example, a plain string template will not help with selective DOM updates; that’s why we end with a tree DSL like JSX.
For many different reasons, you’ll like to have lazy component rendering. That’s why using `Component(props)` is not the same as `factory(Component, props)`.
I’m not saying that the author is wrong or right. If you only want a server-side template or one-off template for a simple page, then using JS/TS string templates is better than relying on a DSL like Handlebars or Pug. The client-side story is a bit different, and that’s why there are so many frameworks for it.