Documentation
¶
Overview ¶
Package partial provides request-aware rendering for Go templates.
Partial trees, Stages, connectors, and template caches are safe to reuse across concurrent renders after configuration is complete. Request-scoped state is carried by RenderContext and is not stored on the reusable Partial configuration.
Configuration methods such as SetFunc, Use, With, SetDot, SetFileSystem, SetConnector, SetResponseHeaders, and extension setup helpers mutate the partial they are called on. Call them before serving requests, or synchronize access externally when changing configuration at runtime.
Index ¶
- Constants
- func AddVary(header http.Header, names ...string)
- func BindContext(ctx context.Context, funcs ...template.FuncMap) template.FuncMap
- func IsReservedFuncName(name string, stages ...RenderStage) bool
- func Layers(fsys fs.FS) []fs.FS
- func Overlay(layers ...fs.FS) fs.FS
- func Render(ctx context.Context, p *Partial) (template.HTML, error)
- func RenderSelf(ctx context.Context, r *http.Request, p *Partial) (template.HTML, error)
- func RenderText(ctx context.Context, p *Partial) (string, error)
- func RenderWithRequest(ctx context.Context, r *http.Request, p *Partial) (template.HTML, error)
- func ReservedFuncNames(stages ...RenderStage) []string
- func WithEventSink(ctx context.Context, sink EventSink) context.Context
- func Write(ctx context.Context, w http.ResponseWriter, r *http.Request, p *Partial) error
- func WriteError(w http.ResponseWriter, r *http.Request, p *Partial, status int, err error) error
- type AsyncEvents
- type Declaration
- type Dot
- type DropPolicy
- type Event
- type EventLevel
- type EventSink
- type EventSinkFunc
- type EventsConfig
- type Factory
- type FailurePolicy
- type FailureResponseError
- type FanoutEventSink
- type ModelFunc
- type NamedContract
- type OOBElements
- type Partial
- func (p *Partial) CheckContracts() error
- func (p *Partial) CheckTemplates(patterns ...string) ([]TemplateProblem, error)
- func (p *Partial) ClearDot() *Partial
- func (p *Partial) Clone() *Partial
- func (p *Partial) Connector() connector.Connector
- func (p *Partial) Defines(file string, name string) (bool, error)
- func (p *Partial) Extension(key any) (any, bool)
- func (p *Partial) FirstExisting(candidates ...string) (string, error)
- func (p *Partial) FirstExistingIn(layers []fs.FS, candidates ...string) (string, error)
- func (p *Partial) Func(name string) (any, bool)
- func (p *Partial) GetBasePath() string
- func (p *Partial) Glob(pattern string) ([]string, error)
- func (p *Partial) HasEntry() (bool, error)
- func (p *Partial) ID(id string) *Partial
- func (p *Partial) IsOOB() bool
- func (p *Partial) Parent() *Partial
- func (p *Partial) ParentID() string
- func (p *Partial) PartialID() string
- func (p *Partial) Response() *connector.ResponseBuilder
- func (p *Partial) SetAlwaysSwapOOB(alwaysSwapOOB bool) *Partial
- func (p *Partial) SetBasePath(basePath string) *Partial
- func (p *Partial) SetChildIncludes(patterns ...string) *Partial
- func (p *Partial) SetConnector(c connector.Connector) *Partial
- func (p *Partial) SetContent(child *Partial) *Partial
- func (p *Partial) SetContract(annotation string, values ...any) *Partial
- func (p *Partial) SetDot(value any) *Partial
- func (p *Partial) SetDotSource(d Dot) *Partial
- func (p *Partial) SetEntry(name string) *Partial
- func (p *Partial) SetEvents(events EventSink) *Partial
- func (p *Partial) SetExtension(key any, value any) *Partial
- func (p *Partial) SetFailurePolicy(policy FailurePolicy) *Partial
- func (p *Partial) SetFileSystem(fs fs.FS) *Partial
- func (p *Partial) SetFunc(funcMaps ...template.FuncMap) *Partial
- func (p *Partial) SetIncludes(patterns ...string) *Partial
- func (p *Partial) SetModel(values ...any) *Partial
- func (p *Partial) SetOOBElements(ids ...string) *Partial
- func (p *Partial) SetOOBElementsFunc(fn func(r *http.Request) OOBElements) *Partial
- func (p *Partial) SetParent(parent *Partial) *Partial
- func (p *Partial) SetResponse(response connector.Response) *Partial
- func (p *Partial) SetResponseHeaders(headers map[string]string) *Partial
- func (p *Partial) SetStatus(status int) *Partial
- func (p *Partial) SetTargetFallback(fallback TargetFallback) *Partial
- func (p *Partial) SetTemplates(templates ...string) *Partial
- func (p *Partial) TemplatePaths() []string
- func (p *Partial) Use(stages ...RenderStage) *Partial
- func (p *Partial) UseTemplateCache(useCache bool) *Partial
- func (p *Partial) With(child *Partial) *Partial
- func (p *Partial) WithOOB(child *Partial) *Partial
- func (p *Partial) WithTemplate(templatePath string) *Partial
- type RenderContext
- func (ctx *RenderContext) Emit(event Event)
- func (ctx *RenderContext) EmitForPartial(p *Partial, event Event)
- func (ctx *RenderContext) FailureResponse() bool
- func (ctx *RenderContext) FailureStatus() int
- func (ctx *RenderContext) OmitOOB()
- func (ctx *RenderContext) ResolveFunc(name string) (any, bool)
- func (ctx *RenderContext) SetFunc(name string, fn any)
- func (ctx *RenderContext) SetFuncResolver(resolve func(name string) (fn any, ok bool))
- func (ctx *RenderContext) TargetResolved() bool
- type RenderKind
- type RenderNext
- type RenderResponse
- type RenderStage
- type RenderStageHooks
- func (h RenderStageHooks) FallbackTemplateFuncNames() []string
- func (h RenderStageHooks) Finalize(ctx *RenderContext, out template.HTML, renderErr error) (template.HTML, error)
- func (h RenderStageHooks) Prepare(ctx *RenderContext) (*RenderContext, error)
- func (h RenderStageHooks) Render(ctx *RenderContext, next RenderNext) (template.HTML, error)
- func (h RenderStageHooks) ResolveTemplateFunc(ctx *RenderContext, name string) (any, bool)
- func (h RenderStageHooks) TemplateFuncNames() []string
- type RenderValues
- type Runtime
- func (r *Runtime) BasePath() string
- func (r *Runtime) CheckContracts(p *Partial) error
- func (r *Runtime) Connector() connector.Connector
- func (r *Runtime) Context() context.Context
- func (r *Runtime) Partial(path string, args ...any) template.HTML
- func (r *Runtime) RenderContext() *RenderContext
- func (r *Runtime) RenderPartial(p *Partial) (template.HTML, error)
- func (r *Runtime) RenderPartialWithFallback(p *Partial) (template.HTML, error)
- func (r *Runtime) RenderWith(kind RenderKind, name string, data any, terminal RenderNext) (template.HTML, error)
- func (r *Runtime) Request() *http.Request
- func (r *Runtime) SetValue(key any, value any)
- func (r *Runtime) URL() *url.URL
- func (r *Runtime) Value(key any) any
- type Sources
- type TargetFallback
- type TemplateFuncFallback
- type TemplateFuncNamer
- type TemplateFuncResolver
- type TemplateProblem
Constants ¶
const ( // EventRenderStart is emitted before a render chain runs. EventRenderStart = "render.start" // EventRenderFinish is emitted after a render chain succeeds. EventRenderFinish = "render.finish" // EventRenderError is emitted after a render chain fails. EventRenderError = "render.error" // EventRenderWriteError is emitted when writing a render response fails. EventRenderWriteError = "render.write_error" // EventRenderOOBError is emitted when an out-of-band child render fails. EventRenderOOBError = "render.oob_error" // EventTemplateMissing is emitted when a helper references a missing template. EventTemplateMissing = "template.missing" // EventTemplateParseError is emitted when parsing or loading templates fails. EventTemplateParseError = "template.parse_error" // EventTemplateExecuteError is emitted when template execution fails. EventTemplateExecuteError = "template.execute_error" // EventFuncProtected is emitted, as a warning with the name in the // "function" field, when SetFunc is given a function templates never // call: one named like a go-partial helper, or like a function a render // stage of the partial or its ancestors gives templates; and when Use // adds a stage that replaces a registered function. EventFuncProtected = "func.protected" // EventContentMissing is emitted when content is called without a content child. EventContentMissing = "content.missing" // EventTargetMissing is emitted when a requested target cannot be resolved. EventTargetMissing = "target.missing" // EventTargetFallback is emitted when the target fallback answers a // request for a target that cannot be resolved; see SetTargetFallback. EventTargetFallback = "target.fallback" // EventContractInvalid is emitted when contract data or helper arguments are invalid. EventContractInvalid = "contract.invalid" )
Variables ¶
This section is empty.
Functions ¶
func AddVary ¶ added in v0.15.0
AddVary adds names to the Vary header, unless it lists them, or "*", already, for a response that depends on those request headers. Names that are empty are left out.
partial.AddVary(w.Header(), connector.CurrentURLHeader(conn))
func BindContext ¶ added in v0.15.0
BindContext returns funcs for templates that go-partial does not execute, such as the text part of an e-mail: functions whose first parameter is a context.Context are given ctx, the others are returned as they are. Later maps replace names of earlier ones. Inside a render, functions the render already bound are reused.
func IsReservedFuncName ¶ added in v0.15.0
func IsReservedFuncName(name string, stages ...RenderStage) bool
IsReservedFuncName reports whether templates cannot be given a function named name: one of ReservedFuncNames(stages...), or a name that starts with an underscore.
func Layers ¶ added in v0.15.0
Layers returns the layers of fsys when it is an Overlay, in the order it looks files up in, and fsys alone otherwise; nil for a nil fsys. Use it to add a layer below an overlay without nesting one overlay in another, which FirstExistingIn would try as one layer:
partial.Overlay(append(partial.Layers(theme), defaults)...)
func Overlay ¶ added in v0.15.0
Overlay returns a file system that looks files up in each layer in turn and uses the first that has them; directories list the files of every layer. Use it to let applications replace templates a package ships, or to add in-memory Sources to a directory of templates:
partial.Overlay(os.DirFS("theme"), defaults)
Overlays of the same layers share their entries in the template cache, so an overlay may be built for every render, as long as its layers are not; see Sources.
func Render ¶ added in v0.9.0
Render renders a partial without an http.Request.
Use Render for tests, offline rendering, and jobs that do not have request data. HTTP handlers should usually use Write, or RenderWithRequest when the caller needs the HTML string instead of a written response.
func RenderSelf ¶ added in v0.15.0
RenderSelf renders the partial itself with request data, whatever target the request asks for: for a part of a page that reaches the browser another way, such as a server-sent event, or a page rendered for a request that was made for another one. Templates see the request as they do with RenderWithRequest; no out-of-band regions are added.
func RenderText ¶ added in v0.15.0
RenderText renders the partial as plain text with text/template, for text that is not HTML, such as the subject and the text part of an e-mail: nothing is escaped. Everything else is as for Render: the partial's file system, includes, entry, dot, @model values, functions (those that take a context.Context receive ctx) and template cache, and the render stages of the partial and its ancestors, which give templates their functions and see RenderKindText. A file can hold the text and the HTML of a message side by side:
mail := partial.NewID("mail", "mail/welcome.gohtml").SetParent(root).SetDot(data)
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"))
Text templates call other templates with {{ template }}, from the files of the partial or of its includes (see SetIncludes); go-partial's {{ partial }} and {{ content }} render HTML.
func RenderWithRequest ¶ added in v0.9.0
RenderWithRequest renders a partial using request-aware connector behavior.
When the connector identifies the request as a partial request, this renders the requested target and appends eligible out-of-band regions. For normal requests it renders the partial itself.
func ReservedFuncNames ¶ added in v0.15.0
func ReservedFuncNames(stages ...RenderStage) []string
ReservedFuncNames returns, sorted, the template function names that SetFunc cannot give templates: go-partial's own helpers, such as partial, content, ctx and url, and the names the given render stages give templates, which replace registered functions of the same name. Names that start with an underscore are reserved as well; see IsReservedFuncName.
func WithEventSink ¶ added in v0.9.0
WithEventSink attaches a request-scoped event sink to ctx.
Request-scoped sinks are fanned out with partial tree sinks configured with Partial.SetEvents. If the sink owns goroutines, the caller still owns closing it, usually with defer in middleware.
If ctx already has a request-scoped sink, the new sink is appended with fanout.
func Write ¶ added in v0.9.0
Write renders a partial and writes the HTTP response.
Write owns the response side of rendering: configured response headers, connector response headers, render-stage response metadata, error fragments, and out-of-band regions are applied here. The response varies with the request headers the connector reads, which Write adds to the Vary header. Unless a header sets it, the content type is text/html; charset=utf-8.
The page is rendered before anything is written. With the FailResponse policy (see SetFailurePolicy), a failing part of the page fails the whole response. When the render fails and an error stage, such as ext/errors, renders a failure response, Write writes it, never cached, and returns a *FailureResponseError; otherwise it writes nothing and returns the error.
func WriteError ¶ added in v0.15.0
WriteError answers r with the failure response of the error stage of p's tree, such as ext/errors, for err, an error that happened outside a render, such as a form post whose handler failed to save it: the error page, or for a partial request the error fragment or flash message, as Write answers a render that failed, written with status. The error stage renders with p's functions, includes and models, so an error template looks as it does for a render that failed. A status of 0 or less is 500, and a nil err the text of the status.
if err := save(r); err != nil {
if werr := partial.WriteError(w, r, root, http.StatusInternalServerError, err); werr != nil {
http.Error(w, "Something went wrong", http.StatusInternalServerError)
}
}
The response is never cached, and varies with the request headers the connector reads. WriteError returns nil when it answered the request. Otherwise it wrote nothing and returns why: err itself when the tree has no error stage that answers it, so the caller answers it another way. A failed write of the answer, as to a client that has gone, is emitted as an EventRenderWriteError event. ext/errors' Respond answers with its built-in markup when no error stage does. The error stage renders with the context of r.
Types ¶
type AsyncEvents ¶ added in v0.9.0
type AsyncEvents struct {
// contains filtered or unexported fields
}
AsyncEvents is a non-blocking event dispatcher backed by a bounded queue.
func NewAsyncEvents ¶ added in v0.9.0
func NewAsyncEvents(cfg EventsConfig, sinks ...EventSink) *AsyncEvents
NewAsyncEvents returns a non-blocking dispatcher for diagnostic events.
func (*AsyncEvents) Close ¶ added in v0.9.0
func (events *AsyncEvents) Close(ctx context.Context) error
Close stops workers after delivering queued events, or returns when ctx ends.
func (*AsyncEvents) Dropped ¶ added in v0.9.0
func (events *AsyncEvents) Dropped() uint64
Dropped returns the number of events dropped by this dispatcher.
func (*AsyncEvents) Emit ¶ added in v0.9.0
func (events *AsyncEvents) Emit(ctx *RenderContext, event Event)
Emit enqueues event without blocking unless configured with Block.
type Declaration ¶ added in v0.15.0
type Declaration struct {
Annotation string
Name string
// Type is the declared Go type as package path and name, also when it
// was written as path/Name.
Type string
}
Declaration is one typed declaration in a template comment, such as "@model Page github.com/acme/app.Page" or "@dot github.com/acme/app.Row". A @dot declaration has the annotation "dot" and no name.
func ParseDeclarations ¶ added in v0.15.0
func ParseDeclarations(sources ...string) ([]Declaration, error)
ParseDeclarations returns the typed declarations of template sources, in the order they appear: the typed roots go-partial binds with SetModel and SetContract, and the @dot types. A root declared twice with one type is listed once; a root declared with two types is an error, as it is when the templates render.
type Dot ¶ added in v0.15.0
type Dot struct {
// contains filtered or unexported fields
}
Dot is the dot of a partial as a value, for code that passes it around before a partial exists, such as in a field of a struct: computed when the partial renders (DotFuncOf), keeping its type for CheckContracts. The zero Dot is no dot. Give it to a partial with SetDotSource.
type Panel struct {
ID string
Dot partial.Dot
}
panel := Panel{ID: "stats", Dot: partial.DotFuncOf(loadStats)}
partial.NewID(panel.ID, "stats.gohtml").SetDotSource(panel.Dot)
func DotFuncOf ¶ added in v0.15.0
DotFuncOf returns a Dot computed by fn only when the partial renders: on the page, or on its own as the target of a partial request. A part of a page whose data is expensive, such as a panel of a dashboard, then costs nothing in responses that leave it out. fn receives the context of the render and is called once per render tree, also when several partials inherit the dot; an error fails the render of the partial. A nil fn is no dot.
As T is known before the dot is computed, CheckContracts checks it against the @dot declaration of the partial's template without calling fn, so it tells whether the partial suits a request without computing its data.
stats := partial.DotFuncOf(func(ctx context.Context) (Stats, error) {
return loadStats(ctx)
})
panel := partial.NewID("stats", "stats.gohtml").SetDotSource(stats)
func (Dot) Model ¶ added in v0.15.0
Model returns the dot as a model, sharing its value: it is computed once per render tree, also when a partial renders it as its dot and a template calls it as a model, such as a layout's dot and the regions that declare it with @model. A Dot of DotFuncOf for an interface type, whose values' type is not known before they are computed, and the zero Dot are no model, the zero ModelFunc, which SetModel ignores.
filled := partial.DotFuncOf(fillView) page.SetDotSource(filled).SetModel(filled.Model())
type DropPolicy ¶ added in v0.9.0
type DropPolicy string
DropPolicy decides what AsyncEvents does when its buffer is full.
const ( // DropNewest drops the incoming event when the queue is full. DropNewest DropPolicy = "drop_newest" // DropOldest drops one queued event to make room for the incoming event. DropOldest DropPolicy = "drop_oldest" // Block waits for queue space or Close. Use only when event loss is worse than render latency. Block DropPolicy = "block" )
type Event ¶ added in v0.9.0
type Event struct {
Time time.Time
Kind string
Level EventLevel
Message string
Error error
Fields map[string]any
TraceID string
SpanID string
ParentSpanID string
PartialID string
ParentID string
Name string
}
Event describes something observable that happened during rendering.
type EventLevel ¶ added in v0.9.0
type EventLevel string
EventLevel describes the severity of a diagnostic event.
const ( // EventDebug is useful for local tracing and lifecycle views. EventDebug EventLevel = "debug" // EventInfo describes normal diagnostic breadcrumbs. EventInfo EventLevel = "info" // EventWarn describes recoverable problems or ignored configuration. EventWarn EventLevel = "warn" // EventError describes render failures or other errors. EventError EventLevel = "error" )
type EventSink ¶ added in v0.9.0
type EventSink interface {
Emit(*RenderContext, Event)
}
EventSink receives diagnostic events. Sinks should be defensive and cheap.
func EventSinkFromContext ¶ added in v0.9.0
EventSinkFromContext returns the request-scoped event sink attached to ctx.
type EventSinkFunc ¶ added in v0.9.0
type EventSinkFunc func(*RenderContext, Event)
EventSinkFunc adapts a function to EventSink.
func (EventSinkFunc) Emit ¶ added in v0.9.0
func (f EventSinkFunc) Emit(ctx *RenderContext, event Event)
Emit sends event to the wrapped function.
type EventsConfig ¶ added in v0.9.0
type EventsConfig struct {
Buffer int
DropPolicy DropPolicy
Workers int
}
EventsConfig configures AsyncEvents.
type Factory ¶ added in v0.10.0
type Factory struct {
// contains filtered or unexported fields
}
Factory creates request-scoped partials from a configured prototype. The returned values are ordinary *Partial instances and can use the complete native API directly.
func NewFactory ¶ added in v0.10.0
NewFactory creates a factory from prototype. Later changes to prototype do not affect the factory.
type FailurePolicy ¶ added in v0.15.0
type FailurePolicy int
FailurePolicy decides what a failing part of a render does to the whole render; see Partial.SetFailurePolicy.
const ( // FailInline renders a failing part of a page, such as the content // child, a {{ partial }} call or a component rendered by a stage, as the // error fragment of the registered error stage, or as an error message, // in place; the rest of the page renders. This is the default. FailInline FailurePolicy = iota // FailResponse fails the whole render when any part of it fails, and // also when a template, child or content partial it asks for is // missing. Render, RenderWithRequest and RenderSelf return the first // failure as their error and no HTML. Write writes no part of the page: // it writes the failure response of a registered error stage, such as // ext/errors, with an error status also for partial requests and // without out-of-band regions, and returns a *FailureResponseError; or // it writes nothing at all and returns the error, so the caller can // answer it. Use it where showing a partly broken page is worse than an // error page, such as on a public website. FailResponse )
type FailureResponseError ¶ added in v0.15.0
FailureResponseError is the error Write returns when a render failed and Write answered the request with the failure response of an error stage, such as ext/errors: the response is written, and the caller must not write another. Without an error stage, Write writes nothing and returns the render error itself. Err is the render error and Status the status written.
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)
}
func (*FailureResponseError) Error ¶ added in v0.15.0
func (e *FailureResponseError) Error() string
func (*FailureResponseError) Unwrap ¶ added in v0.15.0
func (e *FailureResponseError) Unwrap() error
type FanoutEventSink ¶ added in v0.9.0
type FanoutEventSink []EventSink
FanoutEventSink forwards events to multiple sinks.
func FanoutEvents ¶ added in v0.9.0
func FanoutEvents(sinks ...EventSink) FanoutEventSink
FanoutEvents returns a sink that forwards events to each non-nil sink.
func (FanoutEventSink) Emit ¶ added in v0.9.0
func (sinks FanoutEventSink) Emit(ctx *RenderContext, event Event)
Emit sends event to each configured sink.
type ModelFunc ¶ added in v0.15.0
type ModelFunc struct {
// contains filtered or unexported fields
}
ModelFunc is a typed model computed only when a template calls it, as a value: SetModel and SetContract take it with other models, such as from a list of models an application passes around before a partial exists. Make one with ModelFuncOf; the zero ModelFunc is no model, which SetModel ignores.
func ModelFuncOf ¶ added in v0.15.0
ModelFuncOf returns a model of the type T computed by fn only when a template of the partial or of a partial rendered under it calls the model, such as the navigation that a layout, its header and its sidebar each declare with @model Nav github.com/acme/app.Navigation: fn is called once per render tree, also when several partials call the model, and not at all for a response that leaves the templates that declare it out. An error fails the template that calls the model. It is matched by T, as SetModel matches values, without calling fn, also by CheckContracts; T must be a concrete type. A nil fn is no model.
models := []any{user, partial.ModelFuncOf(func(ctx context.Context) (SearchBox, error) {
return searchBox(ctx)
})}
page.SetModel(models...)
type NamedContract ¶ added in v0.9.0
type NamedContract interface {
ContractName() string
}
NamedContract lets values choose their go-doc contract name.
type OOBElements ¶ added in v0.15.0
type OOBElements struct {
// IDs are the IDs of the elements that go out of band, as
// SetOOBElements takes them; none sends the whole output.
IDs []string
// Vary names the request headers the choice depends on, such as the
// header in which the client library sends the URL of the page it
// shows (connector.CurrentURLHeader). Write adds them to the Vary
// header of the response, so caches keep the responses apart; names
// that are empty are left out.
Vary []string
}
OOBElements is what the function of SetOOBElementsFunc chooses for a request: the elements of a region that go out of band, and the request headers the choice depends on.
type Partial ¶
type Partial struct {
// contains filtered or unexported fields
}
Partial stores reusable template, data, and child-tree configuration.
func (*Partial) CheckContracts ¶ added in v0.15.0
CheckContracts reports whether the partial can render with the values it has, without rendering it: every typed root its templates declare, such as @model Page, has exactly one matching value among those set on the partial and its parents, and its dot is of the type the first template declares with @dot. A @dot of any or interface{} accepts every dot. It returns the first problem found, or nil.
Use it to decide whether a partial suits a request before committing to it, for example in a target resolver; see Runtime.CheckContracts for a partial that is not attached to the tree yet.
func (*Partial) CheckTemplates ¶ added in v0.15.0
func (p *Partial) CheckTemplates(patterns ...string) ([]TemplateProblem, error)
CheckTemplates parses every template file of the partial's file system, in every folder, with the functions its renders have: those registered with SetFunc on the partial and its ancestors, go-partial's own helpers, those the render stages of the partial and its ancestors give (see Use) and the typed roots the files declare. It reports every problem, not only the first: a file that does not parse, every call of a function the partial does not have, and every {{template}} that names a template no file defines, each with its file, line and column, and for an Overlay the layer the file comes from. Run it when the application starts, so a template that would fail its renders is known before the first request:
problems, err := root.CheckTemplates()
for _, problem := range problems {
log.Print(problem)
}
patterns choose the files by their base name, as path.Match does, such as "*.tmpl"; without, every file named *.gohtml is a template. Templates render with the templates of other files, such as those of SetIncludes, so a template named in any checked file counts as defined. The error is that of reading the file system; the problems are not errors.
func (*Partial) Clone ¶ added in v0.2.0
Clone returns an independent copy of the partial configuration and child tree.
func (*Partial) Connector ¶ added in v0.15.0
Connector returns the connector the partial uses: its own, its nearest parent's, or connector.NewPartial(nil).
func (*Partial) Defines ¶ added in v0.15.0
Defines reports whether the template file defines a template called name with {{ define }}, such as the "html" part of an e-mail that a partial renders with SetEntry, without parsing it for a render: the scan of the file is the one renders use, kept with the template cache (see UseTemplateCache) and made again without. The file is read from the partial's file system; a missing file or one that does not parse is an error.
if ok, _ := root.Defines("mail/welcome.gohtml", "html"); ok {
html, err = partial.RenderSelf(ctx, nil, mail.SetEntry("html"))
}
func (*Partial) Extension ¶ added in v0.9.0
Extension returns extension-owned data from this partial or its parents.
func (*Partial) FirstExisting ¶ added in v0.15.0
FirstExisting returns the first of candidates that is a file in the partial's file system, such as the template of a page's own type before the default one:
file, err := root.FirstExisting("pages/"+key+".gohtml", "pages/"+kind+".gohtml", "pages/page.gohtml")
With the template cache (see UseTemplateCache) the answer for each candidate is remembered per file system, also when it is missing; without, the file system is asked every time. It returns an error that wraps fs.ErrNotExist when no candidate exists, or the first error other than a missing file.
func (*Partial) FirstExistingIn ¶ added in v0.15.0
FirstExistingIn returns the first of candidates found in layers, trying every candidate in a layer before the next layer: over a theme and a package's defaults, the theme's general template wins over the default specific one, where FirstExisting on Overlay(theme, defaults) would pick the latter.
file, err := root.FirstExistingIn(nil, "pages/"+key+".gohtml", "pages/"+kind+".gohtml")
Without layers, those of the partial's file system are used when it is an Overlay, and the file system itself otherwise; nil layers are skipped. The answers are remembered as FirstExisting remembers them. The name returned is that of the file in the layer, which the overlay serves.
func (*Partial) Func ¶ added in v0.15.0
Func returns the function registered as name with SetFunc on the partial or, failing that, on its nearest ancestor, as SetFunc was given it.
func (*Partial) GetBasePath ¶ added in v0.9.0
GetBasePath returns the configured base path, falling back to parents.
func (*Partial) Glob ¶ added in v0.15.0
Glob returns the template files pattern matches in the partial's file system, as SetIncludes resolves its patterns: with the template cache (see UseTemplateCache) the matches are remembered per file system; without, the file system is asked every time, so new files show. Directories are left out. The slice may be shared: do not change it.
files, err := root.Glob("regions/*.gohtml")
func (*Partial) HasEntry ¶ added in v0.15.0
HasEntry reports whether the partial's first template defines its entry (see SetEntry); without an entry, whether it has a template.
func (*Partial) ID ¶
ID sets the stable ID used for target lookup, child registration, and diagnostics.
func (*Partial) IsOOB ¶ added in v0.9.0
IsOOB reports whether the partial is currently being rendered out-of-band.
func (*Partial) Parent ¶ added in v0.15.0
Parent returns the partial p renders under: the partial it was added to with With, SetContent or WithOOB, or the one set with SetParent; nil for a root.
func (*Partial) ParentID ¶ added in v0.9.0
ParentID returns the ID of the parent partial, if one is attached.
func (*Partial) PartialID ¶ added in v0.9.0
PartialID returns the stable render ID for this partial.
func (*Partial) Response ¶ added in v0.9.0
func (p *Partial) Response() *connector.ResponseBuilder
Response returns a builder for connector-specific response instructions.
func (*Partial) SetAlwaysSwapOOB ¶ added in v0.9.0
SetAlwaysSwapOOB makes this out-of-band partial render on every partial request. A region registered with WithOOB goes out of band with partial requests for the partials below the one it is registered on; one that always swaps also goes with requests for that partial itself, such as a notice a page registers for a toast container of the layout. It then goes after the partial's output, unless the output places it already, such as a layout does with {{ slot }} of exp/slots.
func (*Partial) SetBasePath ¶ added in v0.9.0
SetBasePath sets the base path for the partial.
func (*Partial) SetChildIncludes ¶ added in v0.15.0
SetChildIncludes is SetIncludes for the partials rendered under the partial only, not for the partial itself: a root can give the content, regions and fragments of every page their shared templates, such as a theme's "partials/*.gohtml", without adding them to the parse of its layout.
root := partial.New("layout.gohtml").
SetFileSystem(theme).
SetChildIncludes("partials/*.gohtml")
The patterns of descendants come after those of SetIncludes on the same partial. SetChildIncludes replaces the partial's own child patterns; no patterns removes them.
func (*Partial) SetConnector ¶ added in v0.8.0
SetConnector configures the request connector used by this partial.
func (*Partial) SetContent ¶ added in v0.9.0
SetContent registers the primary content child rendered by the content helper.
func (*Partial) SetContract ¶ added in v0.9.0
SetContract registers typed values for go-doc root declarations. Values are matched by type unless they implement NamedContract. A ModelFunc (see ModelFuncOf) is computed only when a template calls it, and matched by the type it computes.
func (*Partial) SetDot ¶ added in v0.9.0
SetDot sets the root value passed to html/template Execute. Templates receive this value as "." and can still use core render helpers such as ctx, request, url, basePath, runtime, partial, and content. Extension helpers such as debug, locale, and csrf remain available when their FuncMaps and stages are used.
func (*Partial) SetDotSource ¶ added in v0.15.0
SetDotSource sets the dot of the partial to d, computed when the partial renders. The zero Dot removes the dot, as ClearDot does. It replaces SetDot, and SetDot replaces it.
func (*Partial) SetEntry ¶ added in v0.15.0
SetEntry makes the partial render the template defined as name, such as {{ define "html" }} in one of its files, instead of its first file. Use it for a file that defines several parts, such as an e-mail with its subject, text and HTML. The @dot declaration of the first file still types the dot. An empty name renders the first file again.
func (*Partial) SetEvents ¶ added in v0.9.0
SetEvents configures the diagnostic event sink inherited by this partial tree.
func (*Partial) SetExtension ¶ added in v0.9.0
SetExtension stores extension-owned data on this partial.
func (*Partial) SetFailurePolicy ¶ added in v0.15.0
func (p *Partial) SetFailurePolicy(policy FailurePolicy) *Partial
SetFailurePolicy sets what a failing part of a render does to the whole: FailInline (the default) or FailResponse. Children inherit the policy; the policy of the partial passed to Render, RenderWithRequest, RenderSelf or Write decides for its whole render.
func (*Partial) SetFileSystem ¶ added in v0.2.0
SetFileSystem sets the file system for the partial.
func (*Partial) SetFunc ¶ added in v0.9.0
SetFunc registers template functions in the Partial scope. Functions named like a go-partial helper are ignored, and those named like a function a render stage of the partial or its ancestors gives templates are never called (see ReservedFuncNames): for each, the partial's event sink receives an EventFuncProtected warning.
func (*Partial) SetIncludes ¶ added in v0.15.0
SetIncludes adds the templates that match patterns, such as "partials/*.gohtml", to every render of the partial and of the partials rendered under it: its children and content, the partials {{ partial }} renders and those that name it with SetParent. Their templates can call the templates these files define, as if each partial listed the files itself. Patterns are those of fs.Glob, resolved against the file system of the partial being rendered; a partial's patterns come after those of its ancestors, and a file is parsed once, also when several patterns or the partial's own templates name it. With the template cache (see UseTemplateCache) a pattern is resolved once per file system; without, at every render, so new files show.
root := partial.New("layout.gohtml").
SetFileSystem(theme).
SetIncludes("partials/*.gohtml")
SetIncludes replaces the partial's own patterns; no patterns removes them.
func (*Partial) SetModel ¶ added in v0.9.0
SetModel registers values for typed model declarations. Nil values are ignored, so optional models can be passed as they are. A ModelFunc (see ModelFuncOf) is computed only when a template calls the model.
func (*Partial) SetOOBElements ¶ added in v0.15.0
SetOOBElements makes the partial, when it goes out of band with a partial response (see WithOOB and SetAlwaysSwapOOB), send only the elements of its output with these IDs, each swapped out of band on its own with the connector's attributes (see connector.OOBAttrs), rather than its whole output. It suits a region of which a request changes a few elements the application can name, such as the items of a menu that mark the page being shown:
menu.SetOOBElements("menu-about", "menu-contact")
An element inside another one it sends goes along with that one, and an ID that is not the ID of an element in the output is left out. When none of them is, or when the end of an element cannot be told, such as an <li> without its </li>, the whole output goes, as it does without IDs: a region that does not give its elements those IDs keeps working. The region's own element, such as the one that carries {{oobAttr}}, is not sent unless its ID is one of them. Rendered on a full page, the partial is not affected. It replaces SetOOBElementsFunc, and SetOOBElementsFunc replaces it.
func (*Partial) SetOOBElementsFunc ¶ added in v0.15.0
func (p *Partial) SetOOBElementsFunc(fn func(r *http.Request) OOBElements) *Partial
SetOOBElementsFunc is SetOOBElements with the IDs chosen per request by fn, such as the menu items whose state changes from the page the visitor comes from to the page requested. fn is called only when the partial goes out of band, once per response, and not for a full page or a response that leaves the partial out. The headers it names in Vary go to the Vary header of the response then, and only then:
menu.SetOOBElementsFunc(func(r *http.Request) partial.OOBElements {
return partial.OOBElements{
IDs: changedItems(connector.CurrentURL(conn, r), r.URL),
Vary: []string{connector.CurrentURLHeader(conn)},
}
})
A nil fn sends the whole output again. It replaces SetOOBElements, and SetOOBElements replaces it.
func (*Partial) SetParent ¶ added in v0.2.0
SetParent renders the partial under parent without making it one of parent's children: the partial inherits what parent configures, such as its functions, render stages, connector, file system, template cache, failure policy and values for @model declarations, and parent is not changed, so one configured partial can be the parent of many partials rendered at the same time. Partial requests cannot target the partial and parent's templates do not include it; use With for that. A nil parent detaches the partial; a parent that would make the partial its own ancestor is ignored.
card := partial.NewID("card", "card.gohtml").SetDot(data).SetParent(root)
html, err := partial.RenderSelf(ctx, r, card)
func (*Partial) SetResponse ¶ added in v0.9.0
SetResponse configures connector-specific response instructions.
func (*Partial) SetResponseHeaders ¶ added in v0.8.0
SetResponseHeaders configures plain HTTP headers written by Write.
func (*Partial) SetStatus ¶ added in v0.10.0
SetStatus configures the HTTP status written by Write. A zero status clears the local value and falls back to the parent partial, then to net/http's default status.
func (*Partial) SetTargetFallback ¶ added in v0.15.0
func (p *Partial) SetTargetFallback(fallback TargetFallback) *Partial
SetTargetFallback answers partial requests for unknown targets with the fallback partial rather than an error; see TargetFallback. Children inherit the fallback. The response instructions are serialized by the connector, such as HX-Retarget, HX-Reswap and HX-Push-Url for htmx, and written by Write; RenderWithRequest returns the fallback's HTML.
root.SetContent(content).
SetTargetFallback(partial.TargetFallback{ID: "content", PushURL: true})
func (*Partial) SetTemplates ¶ added in v0.10.0
SetTemplates replaces the template paths while preserving the partial's configured filesystem, functions, stages, connector, and cache. It is useful when cloning a configured partial as a request-scoped blueprint.
func (*Partial) TemplatePaths ¶ added in v0.9.0
TemplatePaths returns the template paths configured for this partial.
func (*Partial) Use ¶ added in v0.9.0
func (p *Partial) Use(stages ...RenderStage) *Partial
Use appends stages to this partial's render chain.
The functions a stage gives templates (see TemplateFuncNamer) need no stand-ins registered with SetFunc: templates are parsed with stand-ins for them, which the stage replaces when they execute. A function registered on the partial or its ancestors under such a name is never called: the partial's event sink receives an EventFuncProtected warning.
func (*Partial) UseTemplateCache ¶ added in v0.9.0
UseTemplateCache turns the template cache on or off for the partial and the partials rendered under it: its children, its content, the partials {{ partial }} renders and those that name it with SetParent, unless they set it themselves. A partial that sets nothing uses the setting of its nearest ancestor that does; without one, the cache is off. With the cache, each template is read and parsed once; without, on every render, so edits to template files show. Set it on the root once, for example root.UseTemplateCache(!development).
What the cache learns of a file system, its parses, its scans, which files exist (see FirstExisting) and what include patterns match (see Glob), is kept by the root of the partial tree: its clones, the partials rendered under it and those that name it with SetParent share it. Another root, also one over the same directory or the same map file system, such as a second application in one test process, learns it again: a file added after the first root rendered is seen by a root made later, but not by the first one while its cache is on. Give the partials built per request a configured parent with SetParent, rather than a root of their own, so they share its cache.
func (*Partial) With ¶
With registers a child partial on the partial tree.
Registered children are addressable by ID for partial requests. During a full render, go-partial also includes child templates that are referenced by native Go template calls, such as {{ template "row.gohtml" . }}.
func (*Partial) WithOOB ¶
WithOOB registers an out-of-band child partial on the partial tree. A partial response sends the out-of-band children of a partial in the order WithOOB registered them, so it gives the same bytes on every render; registering an ID again keeps its place.
func (*Partial) WithTemplate ¶ added in v0.9.0
WithTemplate creates a child partial from a template path and registers it on the partial tree. The child ID is inferred from the file name without its extension: "templates/sidebar.gohtml" becomes "sidebar".
type RenderContext ¶ added in v0.9.0
type RenderContext struct {
Context context.Context
Request *http.Request
URL *url.URL
BasePath string
Partial *Partial
Runtime *Runtime
Kind RenderKind
Name string
Data any
Values RenderValues
Error error
Response *RenderResponse
Funcs template.FuncMap
Events EventSink
// contains filtered or unexported fields
}
RenderContext contains request-scoped values exposed by the ctx template helper.
func (*RenderContext) Emit ¶ added in v0.9.0
func (ctx *RenderContext) Emit(event Event)
Emit sends a diagnostic event through the active render context.
func (*RenderContext) EmitForPartial ¶ added in v0.9.0
func (ctx *RenderContext) EmitForPartial(p *Partial, event Event)
EmitForPartial sends an event for a specific partial while preserving the active render context, including request-scoped event sinks.
func (*RenderContext) FailureResponse ¶ added in v0.15.0
func (ctx *RenderContext) FailureResponse() bool
FailureResponse reports, in an error render (see ext/errors), whether the failure response answers the request as a whole, as Write writes it, rather than taking the place of a failing part of a page.
func (*RenderContext) FailureStatus ¶ added in v0.15.0
func (ctx *RenderContext) FailureStatus() int
FailureStatus is, in the error render of WriteError, which answers an error that happened outside a render, the status the response is written with, such as 500 or 429; it is 0 for a render that failed.
func (*RenderContext) OmitOOB ¶ added in v0.15.0
func (ctx *RenderContext) OmitOOB()
OmitOOB answers the partial request being rendered with the target alone, without the out-of-band regions of its ancestors. Render stages that resolve the target of a request, such as exp/slots for a standalone slot, call it in Prepare for targets that are requested on their own.
func (*RenderContext) ResolveFunc ¶ added in v0.15.0
func (ctx *RenderContext) ResolveFunc(name string) (any, bool)
ResolveFunc returns the function name as the render gives it to templates through functions set with SetFunc and SetFuncResolver and through its render stages (see TemplateFuncResolver), such as the function of another stage, from a Render hook: the stages of the render are known once every stage has prepared it. Functions registered on the partial with Partial.SetFunc are not looked up.
func (*RenderContext) SetFunc ¶ added in v0.9.0
func (ctx *RenderContext) SetFunc(name string, fn any)
func (*RenderContext) SetFuncResolver ¶ added in v0.14.0
func (ctx *RenderContext) SetFuncResolver(resolve func(name string) (fn any, ok bool))
SetFuncResolver gives templates functions that are looked up by name, only for the functions a template calls. It suits stages that offer many functions, of which a template calls a few. Functions set with SetFunc come first; a later resolver is asked before an earlier one. As with SetFunc, the names must be known when templates are parsed: register stand-ins for them with Partial.SetFunc.
func (*RenderContext) TargetResolved ¶ added in v0.15.0
func (ctx *RenderContext) TargetResolved() bool
TargetResolved reports whether a render stage resolved the target of the partial request being rendered, replacing Partial in Prepare: a later stage that resolves targets leaves it as it is.
type RenderKind ¶ added in v0.9.0
type RenderKind string
RenderKind identifies the current render task for render stages.
const ( // RenderKindPartial is the normal server-side partial render path. RenderKindPartial RenderKind = "partial" // RenderKindTarget is the core target render path selected by a connector. RenderKindTarget RenderKind = "target" )
const RenderKindText RenderKind = "text"
RenderKindText is the render kind of RenderText.
type RenderNext ¶ added in v0.9.0
type RenderNext func(*RenderContext) (template.HTML, error)
RenderNext calls the next render stage in the chain.
type RenderResponse ¶ added in v0.9.0
RenderResponse stores generic response metadata set by render stages.
type RenderStage ¶ added in v0.9.0
type RenderStage interface {
Prepare(*RenderContext) (*RenderContext, error)
Render(*RenderContext, RenderNext) (template.HTML, error)
Finalize(*RenderContext, template.HTML, error) (template.HTML, error)
}
RenderStage observes or changes a render lifecycle.
Prepare runs before the terminal template render and is the right place to add request-scoped template funcs, resolve context values, or start timing. Render wraps the terminal render and can replace or decorate the produced HTML. Finalize runs after Render, even when Render returned an error, and is the right place for cleanup, metrics, or error response shaping.
type RenderStageHooks ¶ added in v0.9.0
type RenderStageHooks struct {
PrepareFunc func(*RenderContext) (*RenderContext, error)
RenderFunc func(*RenderContext, RenderNext) (template.HTML, error)
FinalizeFunc func(*RenderContext, template.HTML, error) (template.HTML, error)
// ResolveFunc gives templates the stage's functions by name, only
// those a template calls; see TemplateFuncResolver.
ResolveFunc func(ctx *RenderContext, name string) (fn any, ok bool)
// FuncNames lists the template functions the stage sets with
// RenderContext.SetFunc or gives with ResolveFunc, for
// ReservedFuncNames; templates are parsed with stand-ins for them.
FuncNames []string
// FallbackFuncNames lists template functions the stage gives with
// ResolveFunc only where the application registered no function
// of that name with SetFunc: templates are parsed with stand-ins
// for them, a registered function is called instead of the
// stage's, and the names are not reserved, so registering one
// raises no warning. Functions of the stage's own package, such as
// a stand-in it offers for production, do not count as registered;
// see Package. See TemplateFuncFallback.
FallbackFuncNames []string
// Package is the import path of the package that made the stage,
// such as github.com/acme/app/tenant. Functions of that package,
// such as the stand-ins its FuncMap offers for the names the stage
// gives templates, are the stage's own: registering one raises no
// func.protected warning and does not count as registered for
// FallbackFuncNames. When Package is empty, the package is that of
// the hook functions, which is the caller's where the compiler
// inlines the function that returns the stage, so a package that
// offers stand-ins sets it, for example to
// reflect.TypeFor[T]().PkgPath() for a type T of its own.
Package string
}
RenderStageHooks adapts individual lifecycle functions to RenderStage.
func (RenderStageHooks) FallbackTemplateFuncNames ¶ added in v0.15.0
func (h RenderStageHooks) FallbackTemplateFuncNames() []string
FallbackTemplateFuncNames returns FallbackFuncNames; see TemplateFuncFallback.
func (RenderStageHooks) Finalize ¶ added in v0.9.0
func (h RenderStageHooks) Finalize(ctx *RenderContext, out template.HTML, renderErr error) (template.HTML, error)
func (RenderStageHooks) Prepare ¶ added in v0.9.0
func (h RenderStageHooks) Prepare(ctx *RenderContext) (*RenderContext, error)
func (RenderStageHooks) Render ¶ added in v0.9.0
func (h RenderStageHooks) Render(ctx *RenderContext, next RenderNext) (template.HTML, error)
func (RenderStageHooks) ResolveTemplateFunc ¶ added in v0.15.0
func (h RenderStageHooks) ResolveTemplateFunc(ctx *RenderContext, name string) (any, bool)
ResolveTemplateFunc returns the function ResolveFunc gives templates as name; see TemplateFuncResolver.
func (RenderStageHooks) TemplateFuncNames ¶ added in v0.15.0
func (h RenderStageHooks) TemplateFuncNames() []string
TemplateFuncNames returns the template functions the stage sets; see FuncNames and FallbackFuncNames.
type RenderValues ¶ added in v0.9.0
RenderValues stores request-scoped values shared by render stages and helpers.
func (RenderValues) Clone ¶ added in v0.9.0
func (v RenderValues) Clone() RenderValues
func (RenderValues) Get ¶ added in v0.9.0
func (v RenderValues) Get(key any) any
func (RenderValues) Set ¶ added in v0.9.0
func (v RenderValues) Set(key any, value any)
type Runtime ¶ added in v0.9.0
type Runtime struct {
// contains filtered or unexported fields
}
Runtime is the per-render handle passed explicitly to helpers that need request-aware behavior. It keeps application data typed through SetDot while still giving advanced helpers access to the active request, connector, and partial render path.
func RuntimeFrom ¶ added in v0.15.0
RuntimeFrom returns the runtime of the partial whose template is executing in the render of ctx, for functions registered with SetFunc whose first parameter is a context.Context. Such a function can render a partial as a true child of the partial that calls it, with its models, functions, stages and failure policy:
func card(ctx context.Context, data Card) (template.HTML, error) {
runtime, ok := partial.RuntimeFrom(ctx)
if !ok {
return "", errors.New("card: not rendering")
}
return runtime.RenderPartial(partial.NewID("card", "card.gohtml").SetDot(data))
}
It reports false outside a template go-partial executes. The partials of one render execute their templates one after another; a function that renders with ctx on other goroutines passes them the runtime instead.
func (*Runtime) CheckContracts ¶ added in v0.15.0
CheckContracts reports whether p could render here, as a child of the active partial: with the models and contract values of the tree it would render in. See Partial.CheckContracts.
func (*Runtime) Partial ¶ added in v0.9.0
Partial renders a template path through the current partial tree.
func (*Runtime) RenderContext ¶ added in v0.9.0
func (r *Runtime) RenderContext() *RenderContext
RenderContext returns the active render context.
func (*Runtime) RenderPartial ¶ added in v0.9.0
RenderPartial renders a child partial through the current render stage chain.
func (*Runtime) RenderPartialWithFallback ¶ added in v0.9.0
RenderPartialWithFallback renders a partial through the current render stage chain and returns the configured error fragment when rendering fails.
func (*Runtime) RenderWith ¶ added in v0.9.0
func (r *Runtime) RenderWith(kind RenderKind, name string, data any, terminal RenderNext) (template.HTML, error)
RenderWith renders a non-template task through the active render stage chain.
func (*Runtime) Request ¶ added in v0.9.0
Request returns the request for the active render, if any.
type Sources ¶ added in v0.15.0
Sources is a file system of template sources held in memory, by path, such as the default markup a package ships for a template that applications may replace:
defaults := partial.Sources{
"share.gohtml": `<nav class="share">{{ range .Links }}…{{ end }}</nav>`,
}
p := partial.NewID("share", "share.gohtml").
SetFileSystem(partial.Overlay(themeFiles, defaults))
Paths use forward slashes without a leading one, as io/fs paths do; directories are implied by the paths of their files.
The template cache tells file systems apart by identity: create Sources once, such as when the application starts, rather than for every render. A Sources must not change while it is used.
type TargetFallback ¶ added in v0.15.0
type TargetFallback struct {
// ID is the partial rendered instead: the partial that sets the
// fallback, or a child registered on its tree, such as the content
// child.
ID string
// Retarget is the selector the client swaps the response into; "#" + ID
// when empty.
Retarget string
// Swap is how the client swaps it; outerHTML when nil.
Swap *connector.Swap
// PushURL pushes the URL of a GET request to the browser history, so
// the address follows the navigation.
PushURL bool
}
TargetFallback answers partial requests for a target the partial tree cannot resolve, such as a link or form in another page's layout that targets an element this page does not have. Instead of failing, the request is answered as one for the fallback partial, usually the page's content, and the response tells the client to swap it where that partial lives, as a navigation. See Partial.SetTargetFallback.
type TemplateFuncFallback ¶ added in v0.15.0
type TemplateFuncFallback interface {
FallbackTemplateFuncNames() []string
}
TemplateFuncFallback is implemented by render stages that give templates some functions only as a fallback for functions the application did not register; see RenderStageHooks.FallbackFuncNames.
type TemplateFuncNamer ¶ added in v0.15.0
type TemplateFuncNamer interface {
TemplateFuncNames() []string
}
TemplateFuncNamer is implemented by render stages that give templates functions, with RenderContext.SetFunc or as a TemplateFuncResolver, so ReservedFuncNames can list them. RenderStageHooks implements it with its FuncNames.
type TemplateFuncResolver ¶ added in v0.15.0
type TemplateFuncResolver interface {
ResolveTemplateFunc(ctx *RenderContext, name string) (fn any, ok bool)
}
TemplateFuncResolver is implemented by render stages that give templates functions bound to the render, such as one that reads the request. go-partial asks the stages of a render for the functions a template calls, by name, when the template is executed: a render whose templates call none of them costs nothing, unlike functions set with RenderContext.SetFunc in Prepare, which are made for every partial. Functions set with SetFunc or SetFuncResolver come first; a later stage is asked before an earlier one. The names must be known when templates are parsed: templates get stand-ins for those the stage declares with TemplateFuncNamer, as RenderStageHooks does with its FuncNames; register stand-ins for others with Partial.SetFunc. RenderStageHooks implements it with its ResolveFunc.
type TemplateProblem ¶ added in v0.15.0
type TemplateProblem struct {
// File is the template's path in the partial's file system, such as
// "regions/menu.gohtml".
File string
// Layer is, for a file system made with Overlay, the index of the layer
// the file comes from, the first layer 0, as the overlay serves it;
// 0 for any other file system.
Layer int
// Line and Column are where the problem is in the file, counted from 1;
// Column is 0 when the parser does not say.
Line int
Column int
// Func is the function the template calls that the partial does not
// have, such as "newsletterForm"; empty for other problems.
Func string
// Template is the template a {{template}} names that no file defines;
// empty for other problems.
Template string
// Suggestion is the defined function or template whose name is closest
// to Func or Template, such as "newsletterForm" for "newsleterForm";
// empty when none is close.
Suggestion string
// Message says what is wrong, without the position, such as
// `function "newsletterForm" not defined`.
Message string
}
TemplateProblem is a problem CheckTemplates finds in a template file: one a render of the file would fail with.
func (TemplateProblem) Error ¶ added in v0.15.0
func (p TemplateProblem) Error() string
Error is the position and the message, with the suggestion when there is one: `layout.gohtml:69:5: function "newsleterForm" not defined; did you mean "newsletterForm"?`.
func (TemplateProblem) Position ¶ added in v0.15.0
func (p TemplateProblem) Position() string
Position is the problem's position: the file, its line and, when known, its column, such as "layout.gohtml:69:5".
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package clients holds go-partial's browser clients in one file system, for applications that serve, fingerprint and version them with their other assets, such as through an import map:
|
Package clients holds go-partial's browser clients in one file system, for applications that serve, fingerprint and version them with their other assets, such as through an import map: |
|
Package connector tells go-partial how a client library makes its requests and reads its responses: htmx 2 (NewHTMX), htmx 4 (NewHTMX4), Unpoly (NewUnpoly), Turbo (NewTurbo), or plain fetch and tests (NewPartial).
|
Package connector tells go-partial how a client library makes its requests and reads its responses: htmx 2 (NewHTMX), htmx 4 (NewHTMX4), Unpoly (NewUnpoly), Turbo (NewTurbo), or plain fetch and tests (NewPartial). |
|
examples
|
|
|
docs
command
|
|
|
showcase
command
|
|
|
exp
|
|
|
actions
Package actions provides experimental render-time action hooks for partials.
|
Package actions provides experimental render-time action hooks for partials. |
|
csrf
Package csrf provides experimental CSRF token helpers for templates.
|
Package csrf provides experimental CSRF token helpers for templates. |
|
flash
Package flash provides experimental request-scoped flash message helpers.
|
Package flash provides experimental request-scoped flash message helpers. |
|
head
Package head keeps the elements a page writes into the document's <head>, such as <link rel="canonical">, <meta name="description">, alternate and feed links and structured data, right when a partial response swaps only a part of the page.
|
Package head keeps the elements a page writes into the document's <head>, such as <link rel="canonical">, <meta name="description">, alternate and feed links and structured data, right when a partial response swaps only a part of the page. |
|
interactions
Package interactions contains optional client-interaction template helpers.
|
Package interactions contains optional client-interaction template helpers. |
|
localization
Package localization provides experimental locale helpers for templates.
|
Package localization provides experimental locale helpers for templates. |
|
metrics
Package metrics provides an experimental renderer for passive render metrics.
|
Package metrics provides an experimental renderer for passive render metrics. |
|
otel
Package otel adds go-partial's diagnostic events to the active OpenTelemetry span of the render's context, through the event sink of Sink.
|
Package otel adds go-partial's diagnostic events to the active OpenTelemetry span of the render's context, through the event sink of Sink. |
|
pageflow
Package pageflow contains experimental helpers for multi-step page flows.
|
Package pageflow contains experimental helpers for multi-step page flows. |
|
selection
Package selection provides experimental selected-partial rendering helpers.
|
Package selection provides experimental selected-partial rendering helpers. |
|
slots
Package slots provides experimental named regions backed by child partials.
|
Package slots provides experimental named regions backed by child partials. |
|
sse
Package sse provides experimental server-sent event helpers for streaming rendered partials.
|
Package sse provides experimental server-sent event helpers for streaming rendered partials. |
|
target
Package target provides experimental dynamic target resolution.
|
Package target provides experimental dynamic target resolution. |
|
templatehelpers
Package templatehelpers exposes optional convenience helpers for templates.
|
Package templatehelpers exposes optional convenience helpers for templates. |
|
ext
|
|
|
debug
Package debug provides an optional renderer for debug output.
|
Package debug provides an optional renderer for debug output. |
|
errors
Package errors provides an optional renderer for render failures.
|
Package errors provides an optional renderer for render failures. |
|
logger
Package logger adapts go-partial diagnostic events to log/slog.
|
Package logger adapts go-partial diagnostic events to log/slog. |
|
internal
|
|
|
asset
Package asset packages the files go-partial's packages embed, such as their browser clients and stylesheets.
|
Package asset packages the files go-partial's packages embed, such as their browser clients and stylesheets. |
|
csp
Package csp computes the Content-Security-Policy hash sources of the inline elements go-partial writes.
|
Package csp computes the Content-Security-Policy hash sources of the inline elements go-partial writes. |