DEV Community


Template framework for rendering HTML or Vecty components

Jeff Lindsay
Indie maker of many things. Helped pioneer SHDH, webhooks, Hacker Dojo, TIGSource, OpenStack, JWT, Twilio, Docker, Dokku, all incidental. Follow your curiosity
・2 min read

On my path to creating my ideal frontend web framework in Go, I've been experimenting with a template system that works with Vecty. I originally built a prototype that output HTML, like a standard template engine. Then, I adapted it to output Vecty objects and got a proof of concept working with Vecty in browser. But, I really didn't want to make a template system specific to Vecty, especially because there aren't a ton of great templating systems in Go. So, I wanted to make the core functionality neutral to outputting HTML strings or Vecty objects. This took some time to figure out, but I've done it.

While I was at it, I also added an expression evaluator system. Most templating systems need some kind of expression evaluation, which leads to them inventing a new micro-language and having to build up helper functionality from scratch or slowly build up bindings to helpers in the host language. Since structurally this templating system is inspired by Vue templates, which are valid HTML, we just needed a way to evaluate expressions used in directive attributes and interpolation brackets. In Vue this is just JavaScript so I figured why not make it JavaScript here. I grabbed an off-the-shelf Go JavaScript interpreter and made an interface so you can swap out not just different JavaScript implementations, but entirely different language runtimes.

The result is quite ergonomic both in use and in implementation. We build on an HTML parser and make a new Node tree that allows us to write custom directives, custom element parsers, and as I mentioned custom expression evaluators. So really what we have is a templating system framework inspired by Vue templates.

Now that I have this working with an HTML renderer, I'm going back to building a Vecty renderer, which has its own implementation of the basic directives. Custom elements let me wrap how Vecty handles components, and I just need to implement slots and a few other directives and I'll be ready to start building components with Vecty.

Discussion (0)