A walkthrough of building an HTML templating DSL in Lua, motivated by frustrations with Handlebars (verbose syntax, XSS footguns) and Rust macro-based solutions like maud (poor tooling, slow compilation). The post leverages Lua's table syntax sugar — calling functions with table literals without parentheses — to create a clean, composable HTML builder in ~117 lines. Key implementation details include: an Html type to distinguish safe from unsafe strings, automatic HTML escaping, void element handling, alphabetically sorted attributes for determinism, and underscore-to-dash conversion for attribute/tag names. Conditional rendering and loops are handled via plain Lua idioms (and/or, map functions) rather than special template syntax.

28m read timeFrom riki.house
Post cover image
Table of contents
What’s in a template engine?Devising an approach that isn’t ass-backwardsThe Dark Side of the MoonThe part where I do the thingErgonomic improvementsIdioms

Sort: