valfz

Server-rendered apps with Go, templ and HTMX

Rendering HTML with templ

templ components, a layout with children, automatic escaping, the generate step, and rendering a page or a single component from a handler.

lesson
03 of 08
read
12 min

templ is a templating language that compiles to Go. A component becomes a Go function with typed parameters, so a misspelled field is a compile error, and rendering a component is an ordinary method call. This lesson replaces the plain-text responses with a real page: a layout, and inside it a list and forms that work without any JavaScript.

Install and pin

templ has two parts: the templ command, which generates code, and the github.com/a-h/templ module, which the generated code imports. Add the module to the project:

go get github.com/a-h/templ@v0.3.1020
go: added github.com/a-h/templ v0.3.1020

Install the command at the same version (the installation page lists the options) and check it:

templ version
v0.3.1020

The two versions have to match. With the module at v0.3.1001 and the command at v0.3.1020, generation prints a warning and the build then fails on functions the older module does not have:

(!) templ version check: generator v0.3.1020 is newer than templ version v0.3.1001 found in go.mod file, consider running `go get -u github.com/a-h/templ` to upgrade
./links_templ.go:134:51: undefined: templ.ResolveAttributeValue

To pin the command in go.mod as well, run go get -tool github.com/a-h/templ/cmd/templ@v0.3.1020 and call it as go tool templ. The rest of the course writes templ for short.

A layout with children

A .templ file is a Go file with one extra kind of declaration.

layout.templ
package main

templ Page(title string) {
	<!DOCTYPE html>
	<html lang="en">
		<head>
			<meta charset="utf-8"/>
			<meta name="viewport" content="width=device-width, initial-scale=1"/>
			<title>{ title }</title>
		</head>
		<body>
			<header>
				<h1><a href="/links">Reading list</a></h1>
			</header>
			<main>
				{ children... }
			</main>
		</body>
	</html>
}

templ Page(title string) compiles to func Page(title string) templ.Component. Inside the braces, markup is written as markup, and { title } inserts a Go expression. { children... } marks the place where the caller’s content goes, which is what makes Page a layout.

Components for the list

links.templ
package main

import (
	"fmt"
	"net/url"
)

templ LinksPage(links []Link, f Filter) {
	@Page("Reading list") {
		@AddForm()
		@SearchForm(f)
		@LinkList(links)
	}
}

templ AddForm() {
	<form id="add-link" action="/links" method="post">
		<label>URL <input type="url" name="url" required/></label>
		<label>Title <input type="text" name="title" required/></label>
		<label>Note <textarea name="note" rows="2"></textarea></label>
		<button type="submit">Add link</button>
	</form>
}

templ SearchForm(f Filter) {
	<form id="search" action="/links" method="get">
		<input type="search" name="q" value={ f.Query } placeholder="Search" aria-label="Search"/>
		<select name="filter" aria-label="Show">
			<option value="all">All</option>
			<option value="unread" selected?={ f.Status == "unread" }>Unread</option>
			<option value="read" selected?={ f.Status == "read" }>Read</option>
		</select>
		<button type="submit">Search</button>
	</form>
}

templ LinkList(links []Link) {
	<ul id="links">
		for _, l := range links {
			@LinkItem(l)
		}
		if len(links) == 0 {
			<li class="empty">Nothing here yet.</li>
		}
	</ul>
}

templ LinkItem(l Link) {
	<li
		id={ fmt.Sprintf("link-%d", l.ID) }
		if l.Read {
			class="read"
		}
	>
		<a href={ l.URL }>{ l.Title }</a>
		<small>{ host(l.URL) }, { l.CreatedAt.Format("Jan 2") }</small>
		if l.Note != "" {
			<p>{ l.Note }</p>
		}
		<form action={ fmt.Sprintf("/links/%d/toggle", l.ID) } method="post">
			<button type="submit">
				if l.Read {
					Mark unread
				} else {
					Mark read
				}
			</button>
		</form>
	</li>
}

// host returns the host part of a URL, or the raw string if it does not parse.
func host(raw string) string {
	u, err := url.Parse(raw)
	if err != nil || u.Host == "" {
		return raw
	}
	return u.Host
}

The syntax to notice:

  • @Page("Reading list") { ... } calls a component and passes the block as its children. @LinkItem(l) calls one without children.
  • for and if are Go statements, with Go’s scoping.
  • An attribute is either a constant in quotes or a Go expression in braces. selected?={ ... } emits a boolean attribute when the expression is true. An if inside a tag adds attributes conditionally, which is how a read link gets class="read".
  • host is an ordinary Go function. Anything outside a templ block is plain Go.

Each item carries a form that posts to its own toggle URL. This is the control promised in lesson 1: the page tells the browser what can be done with a link and where to send the request. The forms are plain HTML, so the application works with scripts disabled. htmx will later improve on that baseline without replacing it.

Generate

templ generate

This writes layout_templ.go and links_templ.go next to the sources and prints how many files it updated. The generated files are ordinary Go, marked // Code generated by templ - DO NOT EDIT. at the top.

Commit them. With the generated code in the repository, go build, go vet and go test work on a fresh clone without the templ command installed. The cost is that the files can go stale, so a CI job should run templ generate and fail if that changes anything.

During development, templ generate -watch -cmd "go run ." starts the server and regenerates on every save, so a template change shows up on the next request without a manual restart. The files it writes in that mode are meant for development, so run a plain templ generate before you build or commit. The live reload page covers the browser side.

Render from a handler

A component has one method, Render(ctx, w). Add a helper to handlers.go that every HTML response will go through, and delete formatLink:

handlers.go
// render writes a component as a complete HTML response.
func (a *app) render(w http.ResponseWriter, r *http.Request, status int, c templ.Component) {
	var buf bytes.Buffer
	if err := c.Render(r.Context(), &buf); err != nil {
		a.serverError(w, r, err)
		return
	}
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	w.WriteHeader(status)
	buf.WriteTo(w)
}

The helper renders into a buffer first. If a component fails halfway, the client gets a clean 500 from serverError instead of a 200 with half a page. The price is holding one page in memory, which is nothing at this size.

Two handlers change. The imports gain bytes and github.com/a-h/templ and lose fmt.

handlers.go
func (a *app) listLinks(w http.ResponseWriter, r *http.Request) {
	f := Filter{
		Query:  r.URL.Query().Get("q"),
		Status: r.URL.Query().Get("filter"),
	}
	links, err := a.store.List(r.Context(), f)
	if err != nil {
		a.serverError(w, r, err)
		return
	}
	a.render(w, r, http.StatusOK, LinksPage(links, f))
}

func (a *app) showLink(w http.ResponseWriter, r *http.Request) {
	id, ok := pathID(r)
	if !ok {
		http.NotFound(w, r)
		return
	}
	l, err := a.store.Get(r.Context(), id)
	if err != nil {
		a.storeError(w, r, err)
		return
	}
	a.render(w, r, http.StatusOK, LinkItem(l))
}

showLink renders one component with no layout around it. That is a fragment, and the same LinkItem function produces it that the page uses for each row. Nothing asks for the fragment yet. In the next lesson htmx will.

Run go run . and open http://localhost:8792/links in a browser. Adding a link, searching and the “Mark read” buttons all work, each with a full page load. From the terminal, one item looks like this:

curl -s localhost:8792/links/2
<li id="link-2"><a href="https://go.dev/blog/routing-enhancements">Routing Enhancements for Go 1.22</a> <small>go.dev, Nov 29</small> <form action="/links/2/toggle" method="post"><button type="submit">Mark read</button></form></li>

What templ escapes

There is still no validation, which makes it possible to see what happens to hostile input. Create a link with markup in every field:

curl -s localhost:8792/links --data-urlencode 'url=https://example.com/?a=1&b=2' --data-urlencode 'title=<script>alert("hi")</script>' --data-urlencode 'note=Tom & Jerry'
curl -s localhost:8792/links/3
<li id="link-3"><a href="https://example.com/?a=1&amp;b=2">&lt;script&gt;alert(&#34;hi&#34;)&lt;/script&gt;</a> <small>example.com, Nov 29</small> <p>Tom &amp; Jerry</p><form action="/links/3/toggle" method="post"><button type="submit">Mark read</button></form></li>

Text and attribute values are HTML-escaped without any call on your part. Attributes that hold URLs get a second check on the scheme:

curl -s localhost:8792/links --data-urlencode 'url=javascript:alert(1)' --data-urlencode 'title=Click me'
curl -s localhost:8792/links/4
<li id="link-4"><a href="about:invalid#TemplFailedSanitizationURL">Click me</a> <small>javascript:alert(1), Nov 29</small> <form action="/links/4/toggle" method="post"><button type="submit">Mark read</button></form></li>

The href was replaced. The same string inside <small> is harmless text. This protection has limits that matter later in the course: templ knows which standard attributes hold URLs or scripts, but it cannot know that an htmx or Alpine attribute will be evaluated as JavaScript. The rule, stated in templ’s injection attacks page, is to never put user input into such attributes.

The compiler covers a different class of mistake. Misspell a field in links.templ, generate, and the build stops:

./links_templ.go:277:69: l.Titel undefined (type Link has no field or method Titel)

The position refers to the generated file, but the message names the field, which is enough to find it in the source.

The page works, and every click reloads all of it. The next lesson adds htmx so that a click replaces only the part that changed.

Exercises

  1. Delete the closing </small> tag in LinkItem and run templ generate. A correct result: generation fails with parsing error: <small>: close tag not found and a line and column, and the existing links_templ.go is left as it was. Restore the tag.
  2. Notes can be long. Write a Go function truncate(s string, n int) string in links.templ and use it so the list shows at most 80 characters of a note followed by .... A correct result cuts a note of 100 é characters after exactly 80 of them: count characters, not bytes.
  3. Wrap the date in a <time> element with a machine-readable datetime attribute in RFC 3339 format. The output for an item should contain something like <time datetime="2026-11-29T00:12:56+02:00">Nov 29</time>.

keyboard

h
home
w c a
writing, courses, about
n p
next and previous lesson
j k
scroll down and up
g G
top and bottom of the page
t
switch light and dark
?
this help

shortcuts are