go-partial
CategoryTemplate Engines
SubcategoryTemplate Engines
Stars24
Render full pages or targeted partials from one html/template tree, for htmx, Turbo and Unpoly
About go-partial
This large README is shown as a plain-text preview. Read the full README at the source
<p align="center">
<a href="https://docs.gowebthings.com/go-partial">
<img src="./assets/go-partial-logo.png" alt="go-partial" height="70">
</a>
</p>
# go-partial
[](https://pkg.go.dev/github.com/donseba/go-partial)
[](https://codecov.io/gh/donseba/go-partial)
[Documentation](https://docs.gowebthings.com/go-partial) · Part of [go-webthings](https://gowebthings.com/components).
This package provides a request-aware rendering layer for Go templates. It lets applications render full pages or targeted partials from the same registered template tree, with wrapper/content composition, connector headers, OOB output, caching, and typed template-friendly data flow.
`go-partial` grew out of [`go-htmx`](https://github.com/donseba/go-htmx). If you only need htmx's request and response headers, `go-htmx` is the smaller choice; `go-partial` adds the rendering layer. The rendering core stays small; connectors and optional extensions add the browser integration your application needs.
## Features
- **Partial Templates**: Define and render partial templates with typed dot data and functions.
- **Native Template Composition**: Use `{{ template "row.gohtml" . }}` with `SetDot` so reusable sections can render inside a page or as HTMX targets.
- **Wrapper Content**: Use wrapper partials with content children while keeping page data explicit.
- **Template Caching**: Enable caching of parsed templates for improved performance.
- **Out-of-Band Rendering**: Support for rendering out-of-band (OOB) partials.
- **File System Support**: Use custom fs.FS implementations for template file access.
- **Concurrent Rendering**: Configure partial trees up front, then reuse them safely across concurrent requests.
- **Checks**: Check typed contracts with `CheckContracts` and every template file with `CheckTemplates` before the first request.
- **Browser Clients**: Small scripts for flash messages, server-sent events and interactions, with no build step (`clients`).
- **Strict Content-Security-Policy**: Output that works without `'unsafe-inline'` and `'unsafe-eval'`; see Content-Security-Policy.
## Installation
To install the package, run:
```bash
go get github.com/donseba/go-partial
```
## Template functions
Template-facing helpers and accessors are documented in [TEMPLATE_FUNCTIONS.md](TEMPLATE_FUNCTIONS.md).
## Package Shape
The root package is intentionally small: rendering lifecycle, partial trees, runtime context, connectors, Root partial configuration, and core template helpers. Core does not import optional packages.
Optional packages are split by stability:
- `ext/...` contains extension packages that are useful but not required by core, such as `ext/errors` and `ext/debug`.
- `exp/...` contains experimental opt-in features, such as localization, CSRF, flash messages, selection, actions, pageflow, interactions, metrics, OpenTelemetry, slots, head regions, target resolvers, template helpers, and SSE.
Applications choose the pieces they want with `SetFunc(...)`, `Use(...)`, or package-specific setup helpers. A render stage follows the same lifecycle everywhere: `Prepare` can add request-scoped context, `Render` wraps or replaces template rendering, and `Finalize` observes or transforms the result.
A stage gives templates functions bound to the render with `ResolveFunc`: go-partial asks it, by name, only for the functions a template calls, so a page whose templates call none of them pays nothing. Templates are parsed with stand-ins for the names a stage declares in `FuncNames`, so `Use(stage)` is all a stage needs; the `FuncMap()` of the stages of `exp/...` and `ext/...` stays for go-clue's signatures and for templates go-partial does not execute.
```go
partial.RenderStageHooks{
FuncNames: []string{"tenant"},
ResolveFunc: func(ctx *partial.RenderContext, name string) (any, bool) {
if name != "tenant" {
return nil, false
}
return func() string { return tenantFrom(ctx.Context) }, true
},
}
```
`RenderContext.SetFunc` in `Prepare` still works and comes first, but makes the function for every partial the stage prepares.
Render stages may set generic response metadata through `ctx.Response`. `partial.Write` applies that status and those headers after rendering. Templates do not receive helpers for setting headers or status; templates produce HTML.
## Rendering
For partials, prefer the package-level rendering functions:
```go
html, err := partial.Render(ctx, content)
html, err = partial.RenderWithRequest(ctx, r, content)
err = partial.Write(ctx, w, r, content)
```
`partial.Write` owns HTTP response behavior: configured headers, connector response headers, render-stage response metadata, error fragments, and out-of-band regions. `Partial` itself does not render or write responses; pass it to the package functions.
`partial.RenderSelf(ctx, r, p)` renders the partial itself with the request, whatever target the request asks for. Use it for HTML that reaches the browser another way, such as a server-sent event.
`partial.Write` adds the request headers the connector reads to the `Vary` response header (see `connector.VaryHeaders`), so caches keep a page and a fragment of it apart. Unless a header sets it, `Write` sends `Content-Type: text/html; charset=utf-8`.
### Template Cache
`UseTemplateCache(true)` on the root turns the template cache on for the whole tree: children, content, the partials `{{ partial }}` renders and those rendered under the root with `SetParent` use the setting of their nearest ancestor that sets one, unless they set it themselves. One switch on the root so covers development and production:
```go
root.UseTemplateCache(!development)
```
What the cache learns of a file system, its parses, its scans, which files exist and what include patterns match, is kept by the root of the tree and shared by its clones, the partials rendered under it and those that name it with `SetParent`. Another root, also one over the same directory or map file system, such as a second application in one test process, learns it again: it sees a file added after the first root rendered, which the first root, with its cache on, does not. Give partials built per request a configured parent with `SetParent` rather than a root of their own, so they share its cache.
### Shared Includes
`SetIncludes` gives every template of a partial and of the partials rendered under it the templates its patterns match, such as a theme's partials, as if each partial listed the files itself:
```go
root := partial.NewID("shell", "layout.gohtml").
SetFileSystem(theme).
SetIncludes("partials/*.gohtml")
```
Patterns are those of `fs.Glob`, resolved against the file system of the partial being rendered; a file is parsed once, also when several patterns, or the partial's own templates, name it. A partial's patterns come after those of its ancestors. With the template cache a pattern is resolved once per file system; without, at every render, so new files show.
`SetChildIncludes` gives the patterns to the partials rendered under a partial only, not to the partial itself: a root gives the content, regions, fragments and error templates of every page the theme's partials without adding them to the parse of its layout.
```go
root.SetChildIncludes("partials/*.gohtml")
```
`root.Glob(pattern)` returns the files a pattern matches, found as includes are: once per file system with the template cache.
### Data Computed When Needed
`partial.DotFuncOf(fn)` is a dot computed by a function only when the partial renders, on the page or as the target of a partial request, which `SetDotSource` sets. A response that leaves the partial out, such as one for another panel of a dashboard, does not load its data:
```go
stats := partial.DotFuncOf(func(ctx context.Context) (Stats, error) {
return store.Stats(ctx)
})
panel := partial.NewID("stats", "stats.gohtml").SetDotSource(stats)
```
The function receives the render's context and runs once per render tree; an error fails the partial's render. The dot keeps its type, so `CheckContracts` checks it against the template's `@dot` without calling the function. A `partial.Dot` can travel as a value, such as in a field of a struct, before there is a partial.
`partial.ModelFuncOf(fn)` is a typed `@model` value computed only when a template calls it, once per render tree, also when the layout, the header and the sidebar each call it, and not at all for a response that leaves them out. `SetModel` and `SetContract` take it with the other models, also from a list of models an application passes around before there is a partial:
```go
page.SetModel(user, partial.ModelFuncOf(func(ctx context.Context) (Navigation, error) {
return loadNavigation(ctx)
}))
```
```gotemplate
{{/* @model Nav github.com/acme/app.Navigation */}}
<nav>{{ range Nav.Items }}…{{ end }}</nav>
```
It is matched by its type, as `SetModel` values are, also by `CheckContracts`, without calling the function. `SetModel` ignores nil values.
`Dot.Model()` gives a dot as a model that shares its value: a dot of `DotFuncOf` is computed once per render tree when the layout renders it as its dot and the regions call it with `@model`, rather than once for each. A dot of an interface type, whose values' type is not known, is no model.
```go
view := partial.DotFuncOf(loadView)
root.SetDotSource(view).SetModel(view.Model())
```
### Choosing A Template
`FirstExisting` returns the first of several templates that exists in a partial's file system, such as a page's own template before the one of its type and the default:
```go
file, err := root.FirstExisting("pages/"+slug+".gohtml", "pages/"+kind+".gohtml", "pages/page.gohtml")
```
With the template cache, the answer for each candidate is remembered per file system, also when it is missing. Without a match, the error wraps `fs.ErrNotExist`.
Over an `Overlay(theme, defaults)`, `FirstExisting` finds a default specific template before the theme's general one. `FirstExistingIn` tries every candidate in a layer before the next, the layers of the partial's overlay or those it is given:
```go
file, err := root.FirstExistingIn(nil, "screens/"+key+".gohtml", "screens/"+kind+".gohtml")
```
`root.Defines("mail/welcome.gohtml", "html")` reports whether a file defines a template, from the scan renders use, kept with the template cache; `HasEntry()` whether a partial's file defines its entry.
### Rendering Text
`partial.RenderText(ctx, p)` renders a partial with `text/template`, for text that is not HTML, such as the subject and text part of an e-mail, with the file system, includes, functions, `@model` values, stages and template cache of an HTML render:
```go
mail := partial.NewID("mail", "mail/welcome.gohtml").SetParent(root).SetDot(user)
subject, err := partial.RenderText(ctx, mail.SetEntry("subject"))
text, err := partial.RenderText(ctx, mail.SetEntry("text"))
html, err := partial.RenderSelf(ctx, nil, mail.SetEntry("html"))
```
Nothing is escaped. Stages see `partial.RenderKindText`. Text templates call others with `{{ template }}`, from the partial's files and includes; `{{ partial }}` and `{{ content }}` render HTML.
### Rendering Under A Parent
`SetParent` renders a partial under a configured partial without adding it to that partial's children: it inherits the parent's functions, render stages, connector, file system, template cache, failure policy and `@model` values, and the parent is not changed. One configured root can so be the parent of every part an application renders on its own, such as a component, an e-mail or a server-sent event, without cloning it:
```go
card := partial.NewID("card", "card.gohtml").SetDot(data).SetParent(root)
html, err := partial.RenderSelf(ctx, r, card)
```
Requests cannot target such a partial; use `With` for children that can be targeted. `Parent()` returns the partial a partial renders under.
### Rendering A Defined Template
`SetEntry(name)` renders the template a file defines with `{{ define name }}` instead of the file itself, for files that define several parts, such as an e-mail:
```go
html, err := partial.Render(ctx, partial.New("mail/welcome.gohtml").SetEntry("html").SetDot(user))
```
### Failure Policy
By default a failing part of a page, such as the content child or a `{{ partial }}` call, renders as an error fragment in place and the rest of the page renders. Where a partly broken page is worse than an error page, fail the whole response instead:
```go
root.SetFailurePolicy(partial.FailResponse)
```
With `FailResponse`, any failing part, and any template, child or content partial that is missing, fails the render. `Render`, `RenderWithRequest` and `RenderSelf` return the first failure and no HTML. `Write` writes nothing of the page: it writes the failure response of a registered error stage, such as `ext/errors`, or nothing at all, and returns the error so the handler can answer it.
When `Write` wrote a failure response, it returns a `*partial.FailureResponseError` with the status it wrote, so the handler knows not to write another one. A failure response is sent with `Cache-Control: no-store`. With `FailResponse` it keeps an error status for partial requests too, and comes without out-of-band regions; with `FailInline` a partial request gets the error fragment with status 200, so the client swaps it in place.
```go
err := partial.Write(ctx, w, r, page)
var written *partial.FailureResponseError
if err != nil && !errors.As(err, &written) {
http.Error(w, "Something went wrong", http.StatusInternalServerError)
}
```
### Target Fallback
A partial request for a target the tree cannot resolve, such as a link in another page's layout that targets an element this page lacks, fails by default. A target fallback answers it with a partial of the tree instead, and tells the client to swap it where that partial lives, as a navigation:
```go
root.SetContent(content).
SetTargetFallback(partial.TargetFallback{ID: "content", PushURL: true})
```
The fallback renders as if the client had asked for it, with the out-of-band regions of its parents. A slot of `exp/slots` that is requested on its own, such as a list that loads more rows, answers without those regions with `slots.OmitOOB()`. `Write` sends `Retarget` (`#content` by default), `Reswap` (`outerHTML` by default) and, for GET requests with `PushURL`, the request URL through the connector, such as `HX-Retarget`, `HX-Reswap` and `HX-Push-Url` for htmx. Known children and targets a resolver of `exp/target` answers are not affected.
Each answer of the fallback emits a `target.fallback` event at info level, with the `target` asked for and the `fallback` ID; a request the tree cannot answer without a fallback emits a `target.missing` warning. See [OBSERVABILITY.md](OBSERVABILITY.md).
## Metrics Output
`exp/metrics` records render lifecycle data through a small `Sink` interface. Use your own sink for storage, or write JSON lines to any `io.Writer`:
```go
sink := metrics.Fanout(
inMemoryStore,
metrics.NewWriterSink(os.Stdout),
)
root.Use(metrics.Stage(sink, metrics.WithTag("chain", "web")))
```
The writer sink is intentionally plain: it works with stdout, files, buffers, pipes, or app-owned adapters that forward records to SSE, queues, or databases.
`metrics.Outermost()` records only the outermost render of a context, such as a page's layout with everything rendered inside it, instead of every nested partial; the renders inside it then cost no more than a context lookup, which suits metrics that are always on:
```go
root.Use(metrics.Stage(sink, metrics.Outermost()))
```
Metrics records distinguish request identity from flow identity. `WithRequestID` labels the current HTTP request. `WithTraceID` can group related browser work such as a page request and later async or SSE requests. `WithParentRequestID` can link a spawned request back to the request that caused it.
## Diagnostic Events
Core and extensions can emit diagnostic events without owning logging, tracing, or queues. Attach shared consumers to the reusable root partial:
```go
events := partial.NewAsyncEvents(
partial.EventsConfig{Buffer: 256, DropPolicy: partial.DropNewest},
logger.Sink(slog.Default(), logger.WithMinLevel(partial.EventWarn)),
mySink,
)
root := partial.New("templates/shell.gohtml").
SetEvents(events)
```
`ext/logger` adapts events to `log/slog`. `logger.WithLevels(...)` writes only the levels given, such as `partial.EventWarn` without the errors an application logs where it answers them, and `logger.Sink(nil)` writes to `slog.Default()` as it is when each event is written. App-owned sinks can forward the same events to DynamoDB, Kafka, OpenTelemetry, SSE debug pages, files, or any other collector. See [OBSERVABILITY.md](OBSERVABILITY.md) for concrete sink examples.
For request-owned collectors, attach a sink with `partial.WithEventSink(r.Context(), sink)` and close request-owned async dispatchers in middleware.
## Example Applications
A documentation-style site built with `go-partial` is available in [examples/docs](examples/docs).
```bash
go run ./examples/docs
```
Open http://localhost:8091.
An htmx-backed feature showcase with real template files is available in [examples/showcase](examples/showcase).
```bash
go run ./examples/showcase
```
Open http://localhost:8090 to see pages for typed rows, selection partials, actions, flash messages, out-of-band rendering, context helpers, localization, HTMX response headers, server-sent events, live metrics, infinite scroll with cursor-style `X-Action` values, and the optional error page.
## Integrations
Several integrations are available, detailed information can be found in the [INTEGRATIONS.md](INTEGRATIONS.md) file.
- htmx 2 (`connector.NewHTMX`) and htmx 4 (`connector.NewHTMX4`)
- Turbo
- Unpoly
- Partial, for framework-neutral fetch clients and tests
- SSE writer, for streaming rendered HTML patches
### HTMX 4
Choose `connector.NewHTMX4(nil)` on the root partial. The connector reads
`HX-Request-Type` and decodes `HX-Target: main#content` into the partial ID
`content`. Body/select requests and history restoration render the full page.
Use IDs on fragment targets; the tag name alone cannot identify a partial.
Continue to build responses with `ReswapWith(connector.NewSwap()...)`. The
response builder snapshots the options, and the selected connector serializes
scroll/show targets in its own protocol. `NewHTMX` keeps the HTMX 2 syntax;
`NewHTMX4` emits separate `scrollTarget`/`showTarget` modifiers. Raw `Reswap`
strings are sent as supplied, so write those in the selected protocol's syntax.
HTMX 4 removed `HX-Trigger-After-Swap` and `HX-Trigger-After-Settle`; its
connector omits these fields. Use `Trigger` for server events or the browser's
`htmx:after:swap` / `htmx:after:settle` events when timing matters. Stream
interactions emit `hx-sse:connect`; load the pinned **hx-sse extension** and send
unnamed SSE data messages for HTML swaps. Named SSE messages dispatch events.
Browser migration also requires explicit `:inherited` attributes and the new
fetch-based event context. See the [official migration guide](https://four.htmx.org/docs/whats-new-in-htmx-4).
### HTMX 4 protocol audit
The connector's complete header/attribute output was checked against the
[HTMX 4 header reference](https://four.htmx.org/reference/headers/),
[migration reference](https://four.htmx.org/docs/whats-new-in-htmx-4), and the
[swap reference](https://four.htmx.org/reference/attributes/hx-swap).
| Definitions | HTMX 4 behavior |
| --- | --- |
| `HX-Request`, `HX-Boosted`, `HX-Current-URL`, `HX-History-Restore-Request` | Names unchanged; history restores render the document |
| `HX-Request-Type` | `full` renders the document; `partial` renders the target |Frequently Asked Questions
What is go-partial?
go-partial is a Template Engines library for the Go programming language. Render full pages or targeted partials from one html/template tree, for htmx, Turbo and Unpoly
How do I install go-partial?
Install go-partial with the Go module system using `go get donseba/go-partial`. Check the repository for the current installation instructions.
What category does go-partial belong to?
go-partial is listed under Template Engines, specifically Template Engines.