Scapegoat TIL

TIL - How templ Provides IDE Support: A Look Under the Hood

Modern development environments provide features we take for granted - code completion, error highlighting, and the ability to jump to definitions. For templ, a templating language for Go, providing these features required some creative engineering. Let's look at how it works.

templ is a templating language that combines HTML and Go code. While tools already exist to provide IDE support for Go (namely gopls, the Go language server), nothing existed for templ files. Building all these features from scratch would be a massive undertaking.

Instead of reinventing the wheel, templ's developer took an ingenious approach: they built a translation layer that converts templ files into Go code, then leverages Go's existing tooling. Here's how it works:

  1. When you open a .templ file in your editor, templ converts it to Go code behind the scenes
  2. It keeps track of where every piece of code came from using "source maps"
  3. It sends the converted Go code to gopls (Go's language server)
  4. When gopls responds, templ translates the responses back to reference the original templ code

An Example

Let's say you're working on a templ file and request code completion. Here's what happens:

  1. Your editor sends a completion request for position X in your templ file
  2. templ converts that position to the corresponding position in the generated Go code
  3. It asks gopls for completions at that position
  4. When gopls responds with suggestions, templ translates them back to templ context
  5. You see the suggestions in your editor

The Benefits

This approach has several advantages:

  1. Reliability: By using Go's mature tooling, templ gets battle-tested IDE support
  2. Maintainability: The templ team doesn't have to maintain a full language server
  3. Feature completeness: Any feature gopls supports can be adapted for templ

Additional Features

The system also includes some templ-specific features, like HTML tag completion. When you type "<", it provides a list of HTML elements with their common attributes pre-filled.

Technical Implementation

For the technically curious, this is implemented as a proxy server that sits between your editor and gopls. It translates LSP (Language Server Protocol) messages in both directions, maintaining the illusion that your editor is talking directly to a templ-aware language server.