Core concepts14 min read
Templates
Where templates live, how they are loaded and embedded, how they reload in development, slots, built-in and custom functions, and escaping.
Every fragment renders one template. Templates are Go's html/template — the same syntax, the same contextual escaping — with a handful of functions added for the things a fragment needs: its slots, links to other pages, assets, forms and the page's <head>.
<!-- templates/pages/post.html -->
<article>
<h1>{{.Title}}</h1>
<p class="meta">{{formatTime .Published "2 January 2006"}}</p>
{{slot "author"}}
<div class="body">{{.Body}}</div>
</article>
Where templates live
Config.Template says where to find them:
app, err := collage.New(&collage.Config{
Template: collage.TemplateConfig{
Root: "templates",
Extension: ".html",
},
})
Every file under Root whose extension is Extension is a template. Root defaults to ./templates and Extension to .html; files with any other extension are ignored, so a README.md beside the templates is harmless.
A template's name is its path relative to Root, extension included, and that is what a fragment names:
templates/
├── layouts/master.html → "layouts/master.html"
├── pages/post.html → "pages/post.html"
└── fragments/author.html → "fragments/author.html"
collage.NewFragment("author", "fragments/author.html")
Loaded once, checked early
collage.New parses every template into one set, before anything is served. Each kind of mistake is caught at the earliest point it can be:
- A root that does not exist fails
NewwithErrTemplateRootMissing— the most common startup failure there is, and worth telling apart from a template that does not parse. - A template that does not parse, or that calls a function nobody registered, fails
Newwith the file named. - A fragment naming a template that was not loaded fails
RegisterPagewithErrTemplateNotFound, naming the page, the fragment and the path. - A fragment bound into a slot its template never calls fails
RegisterPagewithErrUnknownSlot— see Slots below. - A template that does not fit its data —
{{.Titel}}where the data's type has onlyTitle, a method called with the wrong number of arguments — failsRegisterPagewithErrTemplateType, naming the file, the line and the column. See How templates are checked. - A template
html/templatecannot escape — a<script>string that never closes,{{if}}branches that leave an attribute in different states, a partial that ends inside a tag — failsRegisterPage, naming the page, the fragment and the template.html/templateescapes a template the first time it runs, so such a template would parse cleanly and fail on the first request; an optional fragment would be a section silently missing. Every fragment's root template is escaped once at registration, in the context it renders in, and nothing runs: no data handler, no template function. A partial is escaped as part of the template that includes it, not on its own. - A template that fails while executing — a field of data whose type was not known before the render, a nil pointer, a function returning an error — fails its fragment, and the fragment's failure policy applies. Output is buffered, so a template that fails halfway writes nothing rather than half a fragment.
Because every template is in one set, one template can include another by name:
{{template "partials/byline.html" .}}
The names given with {{define}} share that one namespace across every file, so make them distinctive.
With Root alone, templates are read from disk through os.OpenRoot, so a symlink leading out of the directory is refused rather than followed: New fails with ErrTemplateEscapesRoot, naming the file.
Embedding templates in the binary
A binary that reads its templates from ./templates only runs from a directory that has them. Embed them instead, and it runs from anywhere — a container, a systemd unit, a copy on a server:
//go:embed all:templates
var templatesFS embed.FS
app, err := collage.New(&collage.Config{
Template: collage.TemplateConfig{
FS: templatesFS,
Root: "templates",
Extension: ".html",
},
})
With FS set, Root is a directory inside that filesystem. It is still stripped from every name, which is why it is needed: embed.FS names files by their path in the source tree, and without Root every template would be called templates/pages/post.html.
An empty Root with an FS means the root of the filesystem. The all: prefix makes the embed include files whose names begin with . or _, which a plain //go:embed templates would skip.
collage new scaffolds the same with one filesystem, files, which embeds templates, static and plugins-config.json together and is given as Template.FS.
Reloading in development
In development — Config.DevMode — every template is reparsed before each render. Save a template, and the next request uses it. The framework does not read COLLAGE_DEV: collage dev sets it, and the scaffolded main.go turns it into Config.DevMode.
An embedded set could not do that: its bytes were fixed when the binary was built, and reparsing them changes nothing.
So in development the directory on disk wins over the embedded copy whenever Root exists as a directory relative to the working directory, and the application logs that it chose it. Under collage dev, which runs in your project directory, it always does.
collage.New. Without Template.FS it is the Root directory on disk. With an FS, it is the embedded copy, except in development when Root is also a directory relative to the working directory: then that directory is read instead, and the application logs it. In development every render reparses whichever copy was chosen, so an edit on disk shows on the next request, and an edit to a directory that is not read shows only once the binary is rebuilt.Two other things make an edit show up at once:
- The page cache is never read in development, so a page cached before the edit does not hide it.
- Every development page carries a small script that reloads the browser when a template or a static file changes — or a file in a directory named in
Config.DevWatch, for content such as Markdown that your handlers read from disk.
Since the whole set is reparsed, a syntax error in any one template fails every render until it is fixed — in development, where you will see it straight away, with the file and line in the error.
The checks registration makes are not made again for a template edited after startup — the check against its data's type included, until the next restart: its failure shows on the development error page instead, template, line and cause first.
What a template receives
. is exactly what the fragment's data handler returned, or the value collage.Value gave it, in the Go type the handler or the value declares. A fragment with no data, or whose handler is adapted with collage.Effect, renders with no data. See Data handlers.
type postView struct {
Title string
Published time.Time
Body template.HTML // already sanitised, see below
Tags []string
}
<h1>{{.Title}}</h1>
{{with .Tags}}<p>Tagged {{join ", " .}}</p>{{end}}
A template sees its own fragment's data only. A parent's data is not in scope in a child, and there is no global site object: something every template needs, like the site's name, is data its fragment is given or a function you register.
Slots
{{slot "name"}} renders what the fragment's slot of that name holds, in order, and inserts it as HTML. The children's output is not escaped a second time; each child escaped its own values when it rendered.
<main>{{slot "content"}}</main>
<aside>{{slot "sidebar"}}</aside>
- Calling a slot is what declares it; the fragment's Go code needs no
WithSlotfor it.WithSlotonly makes a slot required, or limits it to one fragment. - A slot that holds nothing renders nothing, whether or not anything was ever bound to it.
- A fragment bound into a slot its template never calls fails registration with
ErrUnknownSlot, naming the slot and the slots the template does call: a typo on either side of the binding would otherwise be a section silently missing from the page. Calls in a template it includes or a block it defines count. A template that names a slot by anything but a literal,{{slot .Which}}, may call any of them, so its fragment is not checked. - A slot inside
{{if}}that the template skips is not rendered, though its fragments' data handlers were already started; see Fragments and slots.
The slot function belongs to the fragment executing the template, so the same {{slot "content"}} means a different slot in each fragment that writes it.
Built-in functions
These are available in every template, alongside html/template's own (printf, len, index, eq and the rest):
| Function | Does |
|---|---|
slot "name" | Renders the fragments in one of this fragment's slots |
pageURL "name" "param" value … | The URL of a registered page or document, in this render's locale |
pageURLIn "locale" "name" … | The same, in exactly the locale given |
localeURL "locale" | This page in another locale, or empty when it has no path there |
actionURL "name" … | An action's URL, in this render's locale |
fragmentURL "page" "fragment" … | A fragment path's URL, in this render's locale |
fragmentURLIn "locale" "page" "fragment" … | The same, in exactly the locale given |
asset "/static/app.css" | A mounted file's content-addressed URL |
stylesheet "/static/app.css" | Declares a stylesheet for the page's <head> |
hoist "head" | Where declarations for an area of the page land. An area's name is letters, digits, _ and -; any other fails the render |
csrfToken | The hidden input carrying a form's forgery token |
safeHTML, safeURL | Mark a string as trusted HTML or URL — escape hatches |
dict "key" value … | Builds a map, to pass several values to {{template}} |
default fallback value | value, or fallback when it is empty. Strings only: another type fails the render |
upper, lower, title | Case conversion |
join sep items | Joins a []string |
formatTime t layout | Formats a time.Time with a Go layout |
withQuery "page" 2 … | This page's URL with query parameters set; "" removes one |
pathEscape s | Escapes a string for one path segment |
json v, pre v | A value as JSON, or in an escaped <pre> block to see what a template was given |
add, sub, mul, div, mod, min, max; addf, subf, mulf, divf | Integer and float64 arithmetic |
trim, replace, contains, hasPrefix, hasSuffix, split, truncate | String functions, the string last so they read in a pipeline |
first, last, seq, keys, hasKey, dig | A list's ends, a range to count over, a map's keys, a value deep in the data |
The link functions are strict: an unknown page name or a missing parameter fails the render instead of producing a broken link. Each function's arguments and behaviour are in Template functions.
Adding your own functions
Config.Template.Funcs adds functions — an html/templateFuncMap — to every template:
import "html/template"
app, err := collage.New(&collage.Config{
Template: collage.TemplateConfig{
FS: templatesFS,
Root: "templates",
Funcs: template.FuncMap{
"money": func(cents int64) string {
return fmt.Sprintf("$%d.%02d", cents/100, cents%100)
},
"readingTime": func(words int) string {
return fmt.Sprintf("%d min read", max(1, words/200))
},
},
},
})
<p>{{money .PriceCents}} · {{readingTime .WordCount}}</p>
- Set it before
New.html/templatecan only call a function whose name was known when the template was parsed, andNewis where parsing happens. A template calling a name nobody registered fails inNew, which is the point: it is a typo you find at startup. - An entry under a built-in's name replaces the built-in — except the twelve that depend on the render:
slot,hoist,asset,stylesheet,csrfToken,pageURL,pageURLIn,localeURL,actionURL,fragmentURL,fragmentURLInandwithQuery. The render engine binds its own of each for every render, so overriding any of them is accepted and has no effect, andNewlogs a warning naming it. - A function cannot see the request. It is registered once for the whole program. Anything that depends on the request, the locale or the user belongs in the data handler, which is where the data comes from anyway.
A plugin can contribute functions too, from its Configure hook — see Writing a plugin. When a plugin and Funcs both define a name, Funcs wins: the application is the one that can see both — for a function the plugin adds per render too. A plugin cannot take a built-in's name at all, nor one of the template language's, such as html or eq.
Escaping
html/template escapes every value for the place it appears: HTML text, an attribute, a URL, inline JavaScript or CSS. A post titled <script>alert(1)</script> is printed as text, and a javascript: URL in an href is replaced with a harmless one. You do not escape anything by hand.
Sometimes a value really is HTML — a post body your CMS sanitised, markup your own code produced. There are two ways to say so:
- Give the field the type
template.HTMLin your view, asBodyis above. The type is the decision, made in Go, where it can be reviewed. - Use
safeHTML(orsafeURLfor a URL) in the template.
Either one switches escaping off for that value. Only use them on content you generated or have sanitised, never on anything a user typed; an unescaped user value is a cross-site scripting hole.
Two built-ins produce HTML that is inserted as is:
{{slot}}, whose children escaped their own values.{{hoist}}, which writes what fragments declared for the page. Therc.HoistTitle,rc.HoistMetaand similar helpers escape what they are given; the underlyingrc.Hoistinserts markup exactly as written, so escaping there is yours. The area's name is not escaped but checked:{{hoist .Area}}with a name that is not letters, digits,_and-fails the render, so a value from a request cannot become markup. See Head and SEO.
pageURL and its siblings escape the parameter values they substitute into a path, and refuse a value of . or .., which a browser would resolve as a step up the path.
Example: a blog post
A blog's post page puts most of this page to work. Each part reaches the page a different way:
| Part | Declared in | Lands in the page through |
|---|---|---|
| The post | pages/post.html | the layout's {{slot "content"}} |
| The author card | fragments/author.html | the post's {{slot "author"}} |
| The post's stylesheet | {{stylesheet}} in the post | the layout's {{hoist "head"}} |
<title> and description | rc.HoistTitle, rc.HoistMeta in the handler | the layout's {{hoist "head"}} |
| Readers' comments | the post's data | {{.Text}}, escaped |
The handlers read the post's slug from the path. The blog package stands for your own data layer:
type comment struct {
Name string
Text string
}
type postView struct {
Title string
Published time.Time
Body template.HTML // rendered and sanitised by your own code
Comments []comment
}
type authorView struct {
Name string
Bio string
}
func loadPost(ctx context.Context, rc *collage.RenderContext) (postView, []string, error) {
slug := rc.Param("slug")
p, err := blog.GetPost(ctx, slug)
if err != nil {
return postView{}, nil, err
}
rc.HoistTitle(p.Title)
rc.HoistMeta("description", p.Summary)
view := postView{Title: p.Title, Published: p.Published, Body: p.Body}
for _, c := range p.Comments {
view.Comments = append(view.Comments, comment{Name: c.Name, Text: c.Text})
}
return view, []string{"post:" + slug}, nil
}
func loadAuthor(ctx context.Context, rc *collage.RenderContext) (authorView, error) {
a, err := blog.AuthorOf(ctx, rc.Param("slug"))
if err != nil {
return authorView{}, err
}
return authorView{Name: a.Name, Bio: a.Bio}, nil
}
The author card is a fragment of its own, bound into the post's author slot:
layout := collage.NewFragment("layout", "layouts/master.html").Build()
author := collage.NewFragment("author", "fragments/author.html").
WithData(collage.Load(loadAuthor)).
Build()
post := collage.NewFragment("post", "pages/post.html").
WithData(collage.LoadTagged(loadPost)).
WithSlotFragment("author", author).
Required().
Build()
page := collage.NewPage("post").
WithLayouts(layout).
WithContent(post).
WithPath("en", "/posts/{slug}").
Build()
if err := app.RegisterPage(page); err != nil {
return err
}
The three templates:
<!-- templates/layouts/master.html -->
<!doctype html>
<html>
<head>
<meta charset="utf-8">
{{hoist "head"}}
</head>
<body>{{slot "content"}}</body>
</html>
<!-- templates/pages/post.html -->
{{stylesheet "/static/post.css"}}
<article>
<h1>{{.Title}}</h1>
<p class="meta">{{formatTime .Published "2 January 2006"}}</p>
{{slot "author"}}
<div class="body">{{.Body}}</div>
<section class="comments">
{{range .Comments}}<p><b>{{.Name}}</b> {{.Text}}</p>{{end}}
</section>
</article>
<!-- templates/fragments/author.html -->
<aside class="author">
<strong>{{.Name}}</strong>
<p>{{.Bio}}</p>
</aside>
/static/post.css must be a file in a mount: {{stylesheet}} links its content-addressed URL, and a path no mount serves fails the render.
content slot, and the author fragment fills the post's author slot. The title and description the post's handler hoists, and the stylesheet its template declares, go up to the layout's hoist "head" marker, which is filled once the whole page has rendered. Inside the post, the title and the readers' comments are escaped; the body, a template.HTML, is inserted as is.What the reader gets
Take a post titled Escaping <script> & friends, and a comment whose text is <script>alert(1)</script>. A request for /posts/escaping answers 200, and the page reads, from <head> to </body> and with blank lines left out:
<head>
<meta charset="utf-8">
<title>Escaping <script> & friends</title><meta name="description" content="What html/template escapes for you"><link rel="stylesheet" href="/static/post.cba296a6afd593e0.css">
</head>
<body>
<article>
<h1>Escaping <script> & friends</h1>
<p class="meta">18 October 2026</p>
<aside class="author">
<strong>Ada</strong>
<p>Writes about templates.</p>
</aside>
<div class="body"><p>Hello <em>world</em></p></div>
<section class="comments">
<p><b>mallory</b> <script>alert(1)</script></p>
</section>
</article>
</body>
- The title is escaped in both places it appears.
rc.HoistTitleescapes it for<title>, and{{.Title}}escapes it for the<h1>. - The comment is text.
{{.Text}}is astring, so the reader's script is printed, not run. - The body is markup. Its type is
template.HTML, so it is inserted as is: it is the one value here whose safety is your code's job. - The stylesheet is in the head, linked by its content-addressed URL, though the post's template declared it inside
<body>.
What registration catches
Write {{.Titel}} for the heading in pages/post.html, and {{.Author}} where the comment loop means {{.Name}}. RegisterPage refuses the page with ErrTemplateType, both findings at once, each with its file, line and column:
collage: page "post": fragment "post" (pages/post.html:4:8): {{.Titel}}: type main.postView has no field or method Titel (did you mean Title?)
collage: page "post": fragment "post" (pages/post.html:9:31): {{.Author}}: type main.comment has no field or method Author
Inside {{range .Comments}}, . is a comment, so the second finding names that type, not the post's.
Bind the author card with a typo instead, WithSlotFragment("autor", author), and RegisterPage fails with ErrUnknownSlot:
collage: unknown slot: page "post" fragment "post" binds into slot "autor", but template "pages/post.html" never calls it; it calls [author]
Neither check judges what safeHTML is given, and registration's escaping pass does not either. {{.Text | safeHTML}} fits its types and passes them all, and it would print the reader's script as markup: keep safeHTML for content you generated or sanitised.