Remix.run Logo
EGreg 2 days ago

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?

acdha 2 days ago | parent | next [-]

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.

mikojan 2 days ago | parent [-]

Could you not achieve the same with a <div hidden>?

dspillett 2 days ago | parent | prev | next [-]

> Just to create document fragments?

Largely, I think. Though I've not got around to actually using them yet myself, so take my understanding with a pinch of salt.

Compared to doing that with non-displayed HTML tags outside a template there are performance benefits (the parser deals with it differently knowing it isn't intended to be an active bit of DOM yet) and convenience benefits (IIRC the contents are not going to be picked up by querySelector/querySelectorAll).

Compared to building document fragments in JS they can be a lot more convenient to create and edit, and keep your design and code less tightly coupled (so a designer on your team who doesn't want to touch JS (or who you don't want messing with your JS!) can easily play with them to a certain extent). Other methods to achieve the same separation may involve an extra build step in deploying your work.

65 2 days ago | parent | prev | next [-]

Alpine.js uses <template> tags for if statements and for loops with stateful data. E.g. <template x-if="myVariable === 1"><div>1</div></template>

Which is a simpler way of thinking about templates, rather than slots and fragments.

EGreg 2 days ago | parent | next [-]

Why not just use handlebars js?

vlad1719 2 days ago | parent | prev [-]

[dead]

Theodores 2 days ago | parent | prev [-]

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.