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 Render(ctx context.Context, p *Partial) (template.HTML, error)
- func RenderWithRequest(ctx context.Context, r *http.Request, p *Partial) (template.HTML, error)
- func WithEventSink(ctx context.Context, sink EventSink) context.Context
- func Write(ctx context.Context, w http.ResponseWriter, r *http.Request, p *Partial) error
- type AsyncEvents
- type DropPolicy
- type Event
- type EventLevel
- type EventSink
- type EventSinkFunc
- type EventsConfig
- type Factory
- type FanoutEventSink
- type NamedContract
- type Partial
- func (p *Partial) ClearDot() *Partial
- func (p *Partial) Clone() *Partial
- func (p *Partial) Extension(key any) (any, bool)
- func (p *Partial) GetBasePath() string
- func (p *Partial) ID(id string) *Partial
- func (p *Partial) IsOOB() bool
- 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) 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) SetEvents(events EventSink) *Partial
- func (p *Partial) SetExtension(key any, value any) *Partial
- func (p *Partial) SetFileSystem(fs fs.FS) *Partial
- func (p *Partial) SetFunc(funcMaps ...template.FuncMap) *Partial
- func (p *Partial) SetModel(values ...any) *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) 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
- type RenderKind
- type RenderNext
- type RenderResponse
- type RenderStage
- type RenderStageHooks
- type RenderValues
- type Runtime
- func (r *Runtime) BasePath() string
- 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
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 when a user function tries to overwrite a protected helper. 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" // EventContractInvalid is emitted when contract data or helper arguments are invalid. EventContractInvalid = "contract.invalid" )
Variables ¶
This section is empty.
Functions ¶
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 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 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.
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 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 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 NamedContract ¶ added in v0.9.0
type NamedContract interface {
ContractName() string
}
NamedContract lets values choose their go-doc contract name.
type Partial ¶
type Partial struct {
// contains filtered or unexported fields
}
Partial stores reusable template, data, and child-tree configuration.
func (*Partial) Clone ¶ added in v0.2.0
Clone returns an independent copy of the partial configuration and child tree.
func (*Partial) Extension ¶ added in v0.9.0
Extension returns extension-owned data from this partial or its parents.
func (*Partial) GetBasePath ¶ added in v0.9.0
GetBasePath returns the configured base path, falling back to parents.
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) 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.
func (*Partial) SetBasePath ¶ added in v0.9.0
SetBasePath sets the base path for the partial.
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.
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) 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) 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.
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) 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.
func (*Partial) UseTemplateCache ¶ added in v0.9.0
UseTemplateCache sets the parsed template cache usage flag for the partial.
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) 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
}
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) SetFunc ¶ added in v0.9.0
func (ctx *RenderContext) SetFunc(name string, fn any)
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" )
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)
}
RenderStageHooks adapts individual lifecycle functions to RenderStage.
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)
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 (*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.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
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. |
|
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. |
|
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
|
|