Rendering Model

templ has no runtime template parser. templ generate turns .templ files into Go code ahead of time; at request time you are only calling functions that write to an io.Writer.

The generate pipeline

  • templ generate compiles every .templ file it finds (recursing through the tree) into a sibling *_templ.go
  • The Go compiler treats generated files like any other code
  • templ generate --watch with --cmd and --proxy gives a live reload loop
  • templ fmt formats .templ files; templ lsp runs the language server

The Component interface

Everything reduces to one method (runtime.go):

type Component interface {
    Render(ctx context.Context, w io.Writer) error
}

Render into anything: an http.ResponseWriter, os.Stdout, a bytes.Buffer, a file. Rendering components to files at build time is the documented path to static/SSG-style output.

Serving over HTTP

templ.Handler wraps a component in a standard http.Handler (handler.go):

mux.Handle("/", templ.Handler(page()))
OptionEffect
templ.WithStatus(code)Response status code
templ.WithContentType(ct)Content-Type header
templ.WithErrorHandler(fn)Custom error handling
templ.WithStreaming()Allow early bytes to flush
templ.WithFragments(ids...)Emit only the requested fragments

Streaming

By default the handler buffers so status and headers can still change during the render. With templ.WithStreaming(), bytes can leave early; call templ.Flush() inside a component to push everything written so far (flush.go).

Gotcha: Once the first bytes flush, you can no longer set status codes or headers. Streaming buys a faster time-to-first-byte at the cost of late header changes - pick deliberately, not by default.

Static rendering and frameworks

Two escape hatches from the live-server model:

  • Static rendering: render components to HTML files at build time for SSG-style sites
  • Framework adapters: templ components work inside other web frameworks; integration docs cover the common ones

Compared to html/template

Aspecttemplhtml/template
Parse stepNone - output is compiled codeParse templates at runtime
Type checkingCompile time, typed parametersRuntime
ErrorsGo errors returned from RenderExecute-time errors
FuncMap indirectionNoneCommon
CostMust regenerate on .templ changeReload templates at runtime