Hey @mevrael! I've only just begun using
<template> itself, due to lacking support in the past in older browsers. One way I used to work around this was by putting my multiline HTML templates inside of
<script type=text/html> tags! It's hidden from the page by default (as are all
<script> tags) and then you can get the
innerHTML from it just like any other element!
how do you attach event handlers? Do you have any more complicated language control statements like "if" in templates, how do you handle them?
Usually I'm using a
<script type=text/html> to hold markup for something like a modal, or part of a widget, so there's not too much interactivity I can expect from within the content itself. If I have a modal button that needs to close…itself, I might do something like
<button onclick="destroyModal('welcome')">×</button> and put the event inline in HTML. If it's something more complex, like a form or something interactive I will attach it to the DOM and then use
document.querySelector('.thing').addEventListener() and add my listener after it's been added to the DOM, right at the time it appears to the user.
if statements and random stuff - here's a spaghetti code version of a template I use to generate semi-random layouts for social media. When you load up the generator there's a textarea, there's also a 'spawn' button. When you load the page it creates 3 semi-random layouts with the content from the
textarea, and every time you hit the 'spawn' button it also adds a new layout. All layouts update live if you type in the box.
In this demo, I stored JS code to be executed as data attributes in the
<template> and use
eval() in JS to execute them. This is not something I normally would link to or share, or put online - it's supposed to be an internal tool we use to produce images, but it gives you a glimpse (as you have already discovered) why standardizing ways to do these things could be a big benefit! Beware, it's a tangle of HTML, CSS, EQCSS, and JS -> http://staticresource.com/template3.html and another similar demo with a different template: http://staticresource.com/template4.html
I'd really like to see your suggestions make an impact on HTML!