Speed Coded HTML Templating Thoughts
const tmpl = `
main
h1 Welcome
hr
nav
button one
button two
button three
hr
p this is a test
p this is another test
textarea hello
ul
li alpha
li beta
li zeta
ul
li organize
li things
li and stuff
hr
footer 2022
`
let htm = parse(tmpl);
document.body.innerHTML += htm
console.log(htm)
function isTag(tag) {
return !/Unknown/.test(document.createElement(tag) + '')
}
function parse(input) {
let lines = input.split(/\n/)
let html = []
let closeTags = []
let lastIndent = 0;
for (let i = 1; i < lines.length; i++) {
let indent = 0;
let tag = '';
let content = ''
let line = lines[i]
let mode = 'start';
for (let j = 0; j < line.length; j++) {
const char = line[j]
if (char == ' ' && mode === 'start') {
indent++;
} else if (char != ' ' && mode != 'content') {
mode = 'tag'
tag += char
} else {
mode = 'content'
content += char;
}
}
if (indent <= lastIndent && closeTags.length > 0) {
let back = lastIndent
while(back >= indent) {
html.push(closeTags.pop())
back -= 2
}
}
if (tag.length > 0) {
let xtra = ''
let origTag = tag;
if (!isTag(tag)) {
tag = 'div'
xtra = ` class="${origTag}" `
}
closeTags.push(`</${tag}>`)
html.push(`<${tag + xtra}>`)
if (content.length > 0) html.push(content)
}
lastIndent = indent;
}
return [...html, ...closeTags.reverse()].join('')
}
Parse a minimalistic html template inspired by the likes of jade, haml, pug etc… This is very speed-coded. I may revisit the same thing with a bit more of an elegant approach in the future.