Embedding JSON in HTML <template> Tags
Probably you shouldn't do this. Just put stuff in a script tag. But, still it's intersting to poke at.
Got a great pointer from this response that points to using tags as data blocks. Very cool.
Ok. Hear me out.
We embed pre-baked JSON in tags.
Something like:
HTML
{
"items": ["alfa", "bravo", "charlie"]
}
{
"items": ["delta", "echo", "foxtrot"]
}
template tags don't output by default.
Output
template tags don't output by default.
Doing Stuff and Things
Data can be pulled in by querying for data-type="json". Parsing values is done by running the . through ..
Putting it all together, we get this:
JavaScript
const data = ;
;
;
;
HTML
Output
Less (Net)work
I like it this a lot. Perfect for times when I've got static JSON (e.g. configs for more functionality on the page). It feels nicer to embed than fetching it with a network call.
-a
Endnotes
Again, maybe probably don't do this. Just throw stuff into a script tag unless you've got a good reason not to.
This idea hit me while working on the next version of bitty. I was setting it up to pull in templates automatically. I realized we can do the same thing with data.
If you know of reasons this might go off the rails, please let me know.
See also this response which suggest using tags as data blocks.
References
A bunch of functionality to support vanilla javascript development. All bundled in a single file.