I'm using the <template> tag heavily in Timelinize[0], which has a fairly sophisticated UI that I'm writing in vanilla JS -- not even jQuery. I use a few libraries (for mapping, datetime, and Bootstrap+Tabler for some nice styles), but that's it.
I wrote some boilerplate JS, yes, but I have complete control over my frontend, and I understand how it works, and I don't need to compile it.
Anyway, it works well so far! The <template> tag is a great way to lay out components and then fill them in with simple JS functions.
One nuance is documented in my code comments:
// Ohhhhhh wow, we need to use firstElementChild when cloning the content of a template tag (!!!!):
// https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/template#avoiding_documentfragment_pitfalls
// I spent way too long on this.
const elem = $(tplSelector);
if (!elem) return;
return elem.content.firstElementChild.cloneNode(true);
Once I figured that out, it's been smooth sailing and very powerful.
Oh, but I haven't cleaned up my code at all yet because I was just experimenting/hustling, so it's a bit spaghetti :) If you go looking, don't mind the mess.
---
[0]: https://github.com/timelinize/timelinize - a self-hosted application for bringing together all your data on your own computer and organizing it onto a single timeline: social media accounts, photo libraries, text messages, GPS tracks, browsing history, and more. Almost ready for its debut...
mariusor · 19m ago
I considered vanilla template initially for building my ActivityPub frontend[1], but in the end the sugar that lit-js adds on top of web components seemed worth the file size overhead.
I've been using template elements a lot recently to render products on my wife's photography blog. The product data gets loaded from a headless MedusaJS instance, plugged into a template that matches her blog's theme, and then dropped into the page. I specifically wanted to avoid reaching for something like React since the page load is already pretty heavy with the size of her images. Template's been pretty easy to use in that respect.
alserio · 1h ago
I was wondering, are template elements a good place to store json data in the page to be consumed by js?
Gualdrapo · 8m ago
For my portfolio (miler.codeberg.page) and the refactor&redesign I'm doing of it (that I hope to finish soon!), I feed some <template>s with data coming from a json that acts like kind of a database. I feel the process of querying nodes and setting their data is still a bit rudimentary in plain JS and it should be a pain in the ass for huge datasets or lots of nodes, but at least with modern JS it is not necessary to fetch the json with a XMLHTTPRequest or something - it can work importing it like a regular JS module, so at least there's that.
What do you mean with shape? Are you concerned about escaping and such?
bsmth · 39m ago
I can imagine if it's deeply nested data, your markup might get complex, but the structure of the HTML doesn't have to mirror the JSON. There's other examples here which might illustrate more how this can look: https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/...
alserio · 34m ago
Thank you. I was looking at a generic way to pass configuration data to custom elements where I cannot know the shape in advance, since another dev can have different requirements. I support data attributes for simple types but i was wondering if allowing arbitraty json objects via other means could be feasible.
hunter2_ · 13m ago
Since JSON is a subset of JavaScript, you can just use a script element, and including the json mime type certainly doesn't hurt:
<script type="application/json" id="myJSONData">
{
"name": "John Doe",
"age": 30
}
</script>
<script>
const data = JSON.parse(document.getElementById('myJSONData').textContent);
console.log(data.name + " is " + data.age); // John Doe is 30
</script>
Note: if the JSON data is loaded remotely via src attribute, this doesn't work because the response will not be available via textContent or any other mechanism [0].
As good as a script element with type application/json.
joeframbach · 18m ago
I wonder if the browser would attempt to validate the contents of a script tag with type json, versus treating it as a blob that would only be validated when parsed/used. And any performance overhead at load time for doing so. Not at a machine at the moment so I can't verify.
alserio · 1h ago
well one difference is that application/json scripts are still subject to CSP policies
unilynx · 1h ago
How so? I don't remember ever having seen issues with this. If anything CSP steers you towards this (instead of inline scripts directly assigning to JS variables)
alserio · 38m ago
I thought I knew but it seems that the CSP story is unclear. I couldn't find an authoritative source for either position
mvdtnz · 1h ago
Reading the first example I'm not really seeing what gains I get from this. It's just as much work to create a table row using the template as doing it from scratch.
anaisbetts · 1h ago
Of course, the goal of the example is to teach using an example that makes sense logically. Templates can be arbitrarily large and obviously as the template gets bigger, the difference between it and manual `document.createElement` calls gets much larger.
phartenfeller · 19m ago
Think of a large template with many attributes like classes and structure.
When you want to render this multiple times you just have to update a few things for the unique instance instead of recreating the structure and classes over and over.
tehbeard · 1h ago
The example is a contrived *simple* example to get the point of it being easily cloneable into DOM nodes you then manipulate.
I agree, this seems more complicated than just defining your template in JS. You have to use JS to interact with them anyway and it's basically a mapping between some well-known strings and a factory to create a DOM node except less flexible. The advantage seems to be only if you don't interact with your templates in JS and use them inline in your HTML.
imiric · 40m ago
There is an untapped potential for building modern web sites by leveraging standard web technologies, such as the template element, and sidestepping a whole bunch of bloated abstractions that plague most modern web frameworks. Essentially, we need the simplicity of old school web development married with modern web features.
There are a few modern libraries and frameworks that trend in this direction: Nue, Datastar, Lit. The DX and UX with these is a breath of fresh air.
I've experimented with this approach myself with Miu[1]. It doesn't quite integrate with Web Components nicely yet, but it's almost there. I have some bones to pick with the WC standard, but that's a separate matter.
My wish is that modern web development can eventually not require any 3rd party libraries or frameworks, just like in the early days. Web developers got used to these because of limitations of native web APIs, but the web has grown leaps and bounds since then. Before the modern workflow became standard, it was magical to open a text editor, and have a functioning web page within a few minutes. No dependencies, no build step, no nonsense. Let's bring that back, please.
What exactly is the point of <template> tag? Just to create document fragments? I mean that’s all you can really do with it in HTML. If you are using JS you can attach shadow dom to any element.
I guess maybe slots for web components is the other point?
Theodores · 25s ago
Good question. Yes there was all that web components stuff that didn't go the HTML5 way, and the template element is definitely a child of that. Since elements that get into the spec can't be removed easily, they do get repurposed instead over time.
acdha · 49m ago
I’ve used it to have the server generate fragments not processed in the normal page load which are then used as templates by JavaScript which populates them. That supported fast initial page loads compared to an SPA while being just as dynamic after being loaded.
This worked pretty well but definitely had some rough edges which I really wish the standards process could’ve focused on. Things like JSX are so much slower / memory intensive but people use them for convenience and it’d be nice to improve the ease-of-use story.
I wrote some boilerplate JS, yes, but I have complete control over my frontend, and I understand how it works, and I don't need to compile it.
Anyway, it works well so far! The <template> tag is a great way to lay out components and then fill them in with simple JS functions.
One nuance is documented in my code comments:
Once I figured that out, it's been smooth sailing and very powerful.Oh, but I haven't cleaned up my code at all yet because I was just experimenting/hustling, so it's a bit spaghetti :) If you go looking, don't mind the mess.
---
[0]: https://github.com/timelinize/timelinize - a self-hosted application for bringing together all your data on your own computer and organizing it onto a single timeline: social media accounts, photo libraries, text messages, GPS tracks, browsing history, and more. Almost ready for its debut...
[1] https://github.com/mariusor/oni
[0] https://stackoverflow.com/questions/17124713/read-response-o...
Maybe a more understandable example for you would be it's use in conjunction with <slot>, shown here: https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/...
There are a few modern libraries and frameworks that trend in this direction: Nue, Datastar, Lit. The DX and UX with these is a breath of fresh air.
I've experimented with this approach myself with Miu[1]. It doesn't quite integrate with Web Components nicely yet, but it's almost there. I have some bones to pick with the WC standard, but that's a separate matter.
My wish is that modern web development can eventually not require any 3rd party libraries or frameworks, just like in the early days. Web developers got used to these because of limitations of native web APIs, but the web has grown leaps and bounds since then. Before the modern workflow became standard, it was magical to open a text editor, and have a functioning web page within a few minutes. No dependencies, no build step, no nonsense. Let's bring that back, please.
[1]: https://github.com/hackfixme/miu
I guess maybe slots for web components is the other point?
This worked pretty well but definitely had some rough edges which I really wish the standards process could’ve focused on. Things like JSX are so much slower / memory intensive but people use them for convenience and it’d be nice to improve the ease-of-use story.