go / html templates

hml is a restricted subset of Haml for Go. It is a package with no dependencies outside the standard library. The parser reads .hml files at runtime. There is no build step.

Why a tree

html/template interpolates values into raw markup, so a forgotten closing tag is expressible. In hml, indentation maps to nesting, the parser builds a tree, and the renderer emits matched pairs. hml cannot express <div><p></div></p>. Hugo Landau makes the argument for tree-based HTML generation.

The subset

Templates read pre-computed fields from the context and nothing else. Formatting and branching live in the handler, where a unit test can reach them:

-# before
- if person["headline"].to_s.strip != ""
  = person["headline"]

-# after
- if person.headline
  = person.headline

The syntax:

%tag, .class, #id, { key: value }   tags and attributes
= field                            escaped output
= name(field)                      app-registered transform
= helper(a, b)                     allowlisted helper call
- if expr / - else if / - else     conditionals
- for item in items                loops (optional index: for i, item)
= render "name", key: val          partials
:javascript / :css                 filter blocks
-#                                 comments
static text with #{field}          escaped interpolation

Method calls on data, hash access, ternaries, case/when, variable assignment, and raw output (!=) are parse errors.

Inline content on a tag's line is a parse error, so nesting is always indentation.

- else if keeps a chain at one indentation level:

- if co.active
  %span.ok
    Active
- else if co.pending
  %span.wait
    Pending
- else
  %span.off
    Closed

A loop names its binding:

%table
  - for i, row in rows
    %tr
      %td
        = i
      %td
        %a{ href: row.edit_url }
          Edit

The API

import "github.com/croaky/hml"

tmpl, err := hml.Parse(src, "views/companies/index.hml", transforms)
if err != nil {
    log.Fatal(err)
}

out, err := tmpl.Render(locals, partialFn)

I parse at startup. A syntax error, or a condition that is a literal and so can never be a bool, fails there, before the process serves a request.

Checking locals

A parsed template reports what it reads, so an app checks its locals at startup:

tmpl.Names()   // free top-level identifiers the template reads
tmpl.Renders() // partials it renders by literal name

Names answers for one file. A partial inherits its caller's locals, so an app follows Renders to check a whole page.

Partials from a library

Render takes an hml.PartialFunc, which returns the partial as a string. RenderContextTo takes an hml.PartialWriter, which writes the partial into the caller's buffer, so a page renders into one buffer. Either one finds the view by its name, so the app does not need to own every view it renders. A Go package can ship views: it embeds its .hml files and exports a PartialWriter. My chart package, github.com/croaky/chart, does this. The app's partial writer passes each name that starts with chart/ to it:

func partial(name string, ctx *hml.Context, w *strings.Builder) error {
	if strings.HasPrefix(name, "chart/") {
		return chart.Partial(name, ctx, w)
	}
	// the app's own views
}

A page renders a chart as it renders any partial:

= render "chart/lines", data: lines

chart.Partial parses each embedded view once, on first use. The package's tests render each view, so a view that does not parse fails there, before an app gets it. The package also passes chart.Partial to its own views, so a chart view renders chart/tip and chart/legend with no help from the app. See web / charts.

Transforms

The engine has no built-in transforms. The app registers each one, and each sanitizes its own output. The renderer emits it unescaped:

transforms := map[string]hml.Transform{
	"markdown": func(s string) string {
		var buf bytes.Buffer
		if err := goldmark.Convert([]byte(s), &buf); err != nil {
			return ""
		}
		return mdPolicy.Sanitize(buf.String())
	},
}

A transform takes exactly one field, so a template cannot assemble its input. A name the map does not hold compiles to a call on a helper that the app injects as a local. So a misspelled transform name is a render error.

Conditions are bools

- if, - else if, and ! require a bool. Anything else is an error that names the view, the line, and the type.

There is no truthiness. The template states a comparison, or the handler computes a bool:

- if co.website != ""
- if co.score > 0
- if co.has_website

&& and || keep truthiness, so title || "Untitled" works in an output or an attribute. In a condition, the same expression is a type error.

Render coverage

Parse checks condition syntax, while a non-bool field in - if fails only at render time. A view that no test renders is never type-checked, and parsing alone does not catch it.

tmpl.HasCondition() identifies views that need a render test, and viewcover finds uncovered ones. My loader calls viewcover.Trace(path), which prints hmltrace: <path> to stdout once per process when HML_TRACE is set. viewcover compares those lines against every .hml file with a condition:

go get -tool github.com/croaky/hml/cmd/viewcover
HML_TRACE=1 go test -v ./... > run.txt
go tool viewcover -views ui/views -trace run.txt

Tracing to stdout keeps Go's test cache valid: go test keys on read environment variables and replays stdout on cache hits, whereas an appended trace file would stay empty on cached runs (see go / test).

Coverage records which views rendered. A covered view can still have untested branches. I keep no allowlist: I test uncovered views and delete unreachable ones.

Attribute contexts

A URL attribute takes a relative URL or http, https, mailto, or tel. A value from data with another scheme renders as about:invalid#ZgotmplZ. html/template writes #ZgotmplZ, but a URL that is only a fragment points to the page itself. So an img src or an icon href that holds it makes the browser load the page a second time. A browser fetches nothing for about:invalid. A test can still search the output for ZgotmplZ.

A string literal with a refused scheme, such as a data: URL, fails at parse time. It can only render the sentinel, so it is a mistake in the template.

An on* attribute or style takes a string literal, or a value the handler marked hml.SafeJS or hml.SafeCSS. A plain dynamic value there is a render error. The mark travels with the value, so a partial means what it meant inline. An interpolated string is data.

Script and style blocks

A :javascript block moves every #{} value out of the script source. The renderer writes one array at the top of the block, encoded with encoding/json/v2 and HTML/JS escapes (<, >, &, U+2028, and U+2029), and each #{} becomes a read of its element:

var __hml_<sha256> = ["7",42];
go(`/users/${__hml_<sha256>[0]}`, __hml_<sha256>[1]);

The array name holds the full SHA-256 hash of its values, so two blocks on one page keep their own arrays and cannot collide. At Parse, hml rewrites any quoted string that holds #{} into a template literal and refuses a :javascript line that ends inside a quoted string or a regular expression. It also refuses #{} in a comment or a regular expression. A :css block accepts only a number or hml.SafeCSS in #{}.

Parse refuses a %script or %style tag whose body holds anything but literal text and comments, including a condition, a loop, a partial, or a nested tag. Dynamic values belong in :javascript, :css, or a data-* attribute.

Output shape

The renderer writes each node on its own line. One exception: a tag whose only child is text holds it on the tag's line, as <a href="/">home</a>. Text on its own line puts a space before the closing tag, and an anchor underlines that space. A pre keeps its whitespace.

Editors

The hml repo also holds a tree-sitter grammar: grammar.js, an external scanner for indentation, and queries under queries/. nvim-treesitter runs tree-sitter generate at install time, so the repo does not commit the parser. See vim / tree-sitter grammar.

Embedding templates

I embed the .hml files in the binary with //go:embed.

Single file

One file as a byte slice:

import _ "embed"

//go:embed views/companies/index.hml
var indexTemplate []byte

Or as a string:

//go:embed views/layout.hml
var layout string

Multiple files

Multiple files into an embed.FS:

import "embed"

//go:embed views/*.hml
var viewsFS embed.FS

func loadTemplate(name string) ([]byte, error) {
    return viewsFS.ReadFile("views/" + name)
}

The ReadFile path includes the directory prefix.

Patterns

Patterns work like filepath.Glob:

//go:embed views/*.hml
var viewsFS embed.FS

//go:embed templates/*.html templates/*.css
var assetsFS embed.FS

Two directives can share a variable:

//go:embed views/*.hml
//go:embed partials/*.hml
var viewsFS embed.FS

HTTP file server

Serve embedded files over HTTP:

import (
    "embed"
    "io/fs"
    "net/http"
)

//go:embed static/*
var staticFS embed.FS

func main() {
    // Strip "static/" prefix so /app.css serves static/app.css
    stripped, _ := fs.Sub(staticFS, "static")
    http.Handle("/", http.FileServer(http.FS(stripped)))
    http.ListenAndServe(":8080", nil)
}

When to use

When not to use

See CDN for cache-busting embedded assets in production web apps.

← All articles