Documentation
¶
Overview ¶
xtemplate extends Go's html/template to be capable enough to define an entire server-side application with a directory of Go templates.
Index ¶
- func AddBlueMondayPolicy(name string, policy *bluemonday.Policy)
- func AddMarkdownConfig(name string, md goldmark.Markdown)
- func FuncFailf(format string, args ...any) (string, error)
- func FuncHumanize(formatType, data string) (string, error)
- func FuncIdx(idx int, arr any) (any, error)
- func FuncMarkdown(input string, configName ...string) (template.HTML, error)
- func FuncReturn() (string, error)
- func FuncSanitizeHtml(policyName string, html string) (template.HTML, error)
- func FuncSplitFrontMatter(input string) (parsedMarkdownDoc, error)
- func FuncTrustAttr(s string) template.HTMLAttr
- func FuncTrustHtml(s string) template.HTML
- func FuncTrustJS(s string) template.JS
- func FuncTrustJSStr(s string) template.JSStr
- func FuncTrustSrcSet(s string) template.Srcset
- func FuncTry(fn any, args ...any) (*result, error)
- func FuncWithArgs(dot any, args ...any) (any, error)
- func GetLogger(ctx context.Context) *slog.Logger
- func GetRequestId(ctx context.Context) string
- type CleanupDotProvider
- type Config
- type CrossOriginConfig
- type Dir
- func (d Dir) Chroot(path string) (Dir, error)
- func (d Dir) Exists(filename string) bool
- func (d Dir) ExistsDir(dirname string) bool
- func (d Dir) Open(filename string) (afero.File, error)
- func (d Dir) Read(name string) (string, error)
- func (d Dir) ReadDir(path string) ([]fs.FileInfo, error)
- func (d Dir) Stat(filename string) (fs.FileInfo, error)
- type DotConfig
- type DotDB
- func (c *DotDB) Commit() (string, error)
- func (c *DotDB) Exec(query string, params ...any) (result sql.Result, err error)
- func (c *DotDB) QueryRow(query string, params ...any) (map[string]any, error)
- func (c *DotDB) QueryRows(query string, params ...any) (iter.Seq[map[string]any], error)
- func (c *DotDB) QueryVal(query string, params ...any) (any, error)
- func (c *DotDB) Rollback() (string, error)
- type DotDBConfig
- type DotDirConfig
- type DotFlags
- type DotFlagsConfig
- type DotFlush
- type DotKV
- type DotNats
- type DotNatsConfig
- type DotReq
- type DotResp
- func (h *DotResp) AddHeader(field, val string) string
- func (h *DotResp) DelHeader(field string) string
- func (h *DotResp) ReturnStatus(status int) (string, error)
- func (d *DotResp) ServeContent(path_ string, modtime time.Time, content any) (string, error)
- func (h *DotResp) SetHeader(field, val string) string
- func (h *DotResp) SetStatus(status int) string
- type DotX
- type ErrorStatus
- type HandlerRoute
- type Instance
- type InstanceRoute
- type InstanceStats
- type NatsConfig
- type Option
- func WithDB(name string, db *sql.DB, opt *sql.TxOptions) Option
- func WithDir(name string, fs afero.Fs) Option
- func WithFlags(name string, flags map[string]string) Option
- func WithFuncMaps(fm ...template.FuncMap) Option
- func WithHandler(pattern string, h http.Handler) Option
- func WithLogger(logger *slog.Logger) Option
- func WithNats(name string, serverOpts *server.Options, connOpts *nats.Options, ...) Option
- func WithProvider(p DotConfig) Option
- func WithTemplateFS(fs afero.Fs) Option
- type Request
- type ReturnError
- type Server
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func AddBlueMondayPolicy ¶ added in v0.5.0
func AddBlueMondayPolicy(name string, policy *bluemonday.Policy)
AddBlueMondayPolicy adds a bluemonday policy to the global policy list available to all xtemplate instances.
func AddMarkdownConfig ¶ added in v0.9.0
AddMarkdownConfig adds a custom markdown configuration to xtemplate's markdown config map, available to all xtemplate instances.
func FuncHumanize ¶ added in v0.5.0
humanize transforms size and time inputs to a human readable format using the go-humanize library.
Call with two parameters: format type and value to format. Supported format types are:
"size" which turns an integer amount of bytes into a string like "2.3 MB", for example:
{{humanize "size" "2048000"}}
"time" which turns a time string into a relative time string like "2 weeks ago", for example:
{{humanize "time" "Fri, 05 May 2022 15:04:05 +0200"}}
func FuncIdx ¶ added in v0.5.0
idx gets an item from a list, similar to the built-in index, but with reversed args: index first, then array. This is useful to use index in a pipeline, for example:
{{generate-list | idx 5}}
Returns an error if the value is not indexable or the index is out of range.
func FuncMarkdown ¶ added in v0.5.0
markdown renders the given Markdown text as HTML and returns it. This uses the Goldmark library, which is CommonMark compliant. If an alternative markdown policy is not named, it uses the default policy which has these extensions enabled: Github Flavored Markdown, Footnote, and syntax highlighting provided by Chroma.
func FuncReturn ¶ added in v0.5.0
return causes the template to exit early with a success status.
func FuncSanitizeHtml ¶ added in v0.5.0
sanitizeHtml Uses the BlueMonday library to sanitize strings with html content. First parameter is the name of the chosen sanitization policy.
func FuncSplitFrontMatter ¶ added in v0.5.0
splitFrontMatter parses front matter out from the beginning of input, and returns the separated key-value pairs and the body/content. input must be a "stringy" value.
func FuncTrustAttr ¶ added in v0.5.0
trustAttr marks the string s as safe and does not escape its contents in html attribute context.
func FuncTrustHtml ¶ added in v0.5.0
trustHtml marks the string s as safe and does not escape its contents in html node context.
func FuncTrustJS ¶ added in v0.5.0
trustJS marks the string s as safe and does not escape its contents in script tag context.
func FuncTrustJSStr ¶ added in v0.5.0
trustJSStr marks the string s as safe and does not escape its contents in script expression context.
func FuncTrustSrcSet ¶ added in v0.5.0
trustSrcSet marks the string s as safe and does not escape its contents in script tag context.
func FuncTry ¶ added in v0.5.0
The try template func accepts a fallible function object and calls it with the provided args. If the function and args are valid, try returns the result wrapped in a result object that exposes the return value and error to templates. Useful if you want to call a function and handle its error in a template. If the function value is invalid or the args cannot be used to call it then try raises an error that stops template execution.
func FuncWithArgs ¶ added in v0.9.0
withArgs attaches extra arguments to the dot value so they can be passed to a sub-template, working around Go's restriction that the {{template}} action accepts only a single data argument. It returns a wrapper struct that embeds the original dot (so all of its fields and methods remain accessible) and exposes the extra arguments as a .Args slice. For example:
{{template "head" withArgs . "Post not found"}}
and inside the "head" template:
<title>{{.Args | idx 0}}</title>
{{.X.StaticFileHash "/assets/style.css"}}
Calling withArgs on an already-wrapped dot replaces .Args rather than nesting, keeping the embedded dot flat. The dot must be a struct.
func GetRequestId ¶ added in v0.6.0
Types ¶
type CleanupDotProvider ¶ added in v0.5.0
type Config ¶ added in v0.3.0
type Config struct {
// The path to the templates directory within the filesystem. Default `templates`.
TemplatesDir string `json:"templates_dir,omitempty" arg:"-t,--template-dir,--templates-dir" default:"templates"`
// The FS to load templates from. Default: a FS made from the current working directory.
TemplatesFS afero.Fs `json:"-" arg:"-"`
// File extension to search for to find template files. Default `.html`.
TemplateExtension string `json:"template_extension,omitempty" arg:"--template-ext" default:".html"`
// Whether html templates are minified at load time. Default `true`.
//
// This is a *bool so that Defaults() can distinguish "unset" (nil, which
// becomes true) from an explicit false. A plain bool could not: Server and
// Instance re-apply Defaults internally, so a zero-valued false would be
// indistinguishable from unset and could never be honored, and the
// documented default of true would only hold when constructing via New().
Minify *bool `json:"minify,omitempty" arg:"-m,--minify" default:"true"`
CrossOrigin CrossOriginConfig `json:"crossorigin" arg:"-"`
Databases []DotDBConfig `json:"databases" arg:"-"`
Flags []DotFlagsConfig `json:"flags" arg:"-"`
Directories []DotDirConfig `json:"directories" arg:"-"`
Nats []DotNatsConfig `json:"nats" arg:"-"`
CustomProviders []DotConfig `json:"-" arg:"-"`
// Left template action delimiter. Default `{{`.
LDelim string `json:"left,omitempty" arg:"--ldelim" default:"{{"`
// Right template action delimiter. Default `}}`.
RDelim string `json:"right,omitempty" arg:"--rdelim" default:"}}"`
// Additional functions to add to the template execution context.
FuncMaps []template.FuncMap `json:"-" arg:"-"`
// Custom HTTP handlers, mounted on the router alongside template and static
// file routes. Registered on every instance, so they survive reloads.
Handlers []HandlerRoute `json:"-" arg:"-"`
// The instance context that is threaded through dot providers and can
// cancel the server. Defaults to `context.Background()`.
Ctx context.Context `json:"-" arg:"-"`
// The default logger. Defaults to `slog.Default()`.
Logger *slog.Logger `json:"-" arg:"-"`
// Reload, when non-nil, triggers server.Reload(opts...) on each receive.
// Send options to mutate the config for that reload (e.g. WithTemplateFS to
// swap the templates source). Send nil to reload in place. Close the channel
// to stop the consumer. The caller owns the source and any debounce.
//
// Options apply to a copy of the config per reload, so they are not sticky:
// the next reload starts from the original config again. Use a single reload
// source per server unless you persist options into the base config yourself.
Reload <-chan []Option `json:"-" arg:"-"`
}
func (*Config) Instance ¶ added in v0.4.0
func (config *Config) Instance(cfgs ...Option) (*Instance, *InstanceStats, []InstanceRoute, error)
Instance creates a new *Instance from the given config
func (*Config) SetDefaults ¶ added in v0.9.0
FillDefaults sets default values for unset fields
type CrossOriginConfig ¶ added in v0.9.0
type Dir ¶ added in v0.8.0
type Dir struct {
// contains filtered or unexported fields
}
Dir
func (Dir) Chroot ¶ added in v0.9.0
Chroot returns a copy of the filesystem with root changed to path.
func (Dir) Read ¶ added in v0.8.0
Read returns the contents of a filename relative to the FS root as a string.
type DotConfig ¶ added in v0.5.0
type DotConfig interface {
FieldName() string
Init(context.Context) error
// Value returns the value to assign to this provider's dot field for a
// given request. It must return a stable, non-nil concrete type: makeDot
// calls it once with a mock request purely to infer the field type via
// reflection, so a nil return (e.g. on error during inference) cannot be
// used to build the dot struct.
Value(Request) (any, error)
}
type DotDB ¶ added in v0.8.0
type DotDB struct {
// contains filtered or unexported fields
}
DotDB is used to create a dot field value that can query a SQL database. When any of its statement executing methods are called, it creates a new transaction. When template execution finishes, if there were no errors it automatically commits any uncommitted transactions remaining after template execution completes, but if there were errors then it calls rollback on the transaction.
func (*DotDB) Commit ¶ added in v0.8.0
Commit manually commits any implicit transactions opened by this DotDB. This is called automatically if there were no errors at the end of template execution.
func (*DotDB) Exec ¶ added in v0.8.0
Exec executes a statement with parameters and returns the raw sql.Result. Note: this can be a bit difficult to use inside a template, consider using other methods that provide easier to use return values.
func (*DotDB) QueryRow ¶ added in v0.8.0
QueryRow executes a query, which must return one row, and returns it as a map[string]any.
func (*DotDB) QueryRows ¶ added in v0.8.0
QueryRows executes a query and returns an iterator that yields one map[string]any per result row. Rows are scanned lazily as the sequence is consumed instead of being buffered up front, so a `{{range}}` over the result only holds a single row in memory at a time.
Errors that occur before iteration starts (opening the transaction, executing the query, reading column metadata) are returned directly. Errors that occur while scanning rows can't be returned from the iterator, so they are raised via panic(template.ExecError{...}); the template engine recovers these and returns them from template execution, aborting it just like a normal error return would.
type DotDBConfig ¶ added in v0.8.0
type DotDBConfig struct {
*sql.DB `json:"-"`
*sql.TxOptions `json:"-"`
Name string `json:"name"`
Driver string `json:"driver"`
Connstr string `json:"connstr"`
MaxOpenConns int `json:"max_open_conns"`
}
func (*DotDBConfig) Cleanup ¶ added in v0.8.0
func (dp *DotDBConfig) Cleanup(v any, err error) error
func (*DotDBConfig) FieldName ¶ added in v0.8.0
func (d *DotDBConfig) FieldName() string
type DotDirConfig ¶ added in v0.8.0
type DotDirConfig struct {
Name string `json:"name"`
Path string `json:"path"`
Type string `json:"type"`
FS afero.Fs `json:"-"`
}
DotDirConfig can configure an xtemplate dot field to provide file system access to templates. You can configure xtemplate to use it three ways:
By setting a cli flag: “
func (*DotDirConfig) Cleanup ¶ added in v0.8.0
func (p *DotDirConfig) Cleanup(a any, err error) error
func (*DotDirConfig) FieldName ¶ added in v0.8.0
func (c *DotDirConfig) FieldName() string
type DotFlagsConfig ¶ added in v0.8.0
func (*DotFlagsConfig) FieldName ¶ added in v0.8.0
func (d *DotFlagsConfig) FieldName() string
type DotFlush ¶ added in v0.5.0
type DotFlush struct {
// contains filtered or unexported fields
}
DotFlush is used as the .Flush field for flushing template handlers (SSE).
func (*DotFlush) Flush ¶ added in v0.5.0
Flush flushes any content waiting to written to the client.
func (*DotFlush) Repeat ¶ added in v0.5.0
Repeat generates numbers up to max, using math.MaxInt64 if no max is provided.
func (*DotFlush) SendSSE ¶ added in v0.6.0
SendSSE sends an sse message by formatting the provided args as an sse event:
Requires 1-4 args: event, data, id, retry
func (*DotFlush) WaitForServerStop ¶ added in v0.5.0
WaitForServerStop blocks execution until the request is canceled by the client or until the server closes.
type DotNatsConfig ¶ added in v0.8.0
type DotNatsConfig struct {
Name string `json:"name"`
*NatsConfig `json:"nats_config"`
Conn *nats.Conn
// contains filtered or unexported fields
}
func (*DotNatsConfig) FieldName ¶ added in v0.8.0
func (d *DotNatsConfig) FieldName() string
type DotReq ¶ added in v0.5.0
DotReq is used as the .Req field for template invocations with an associated request, and contains the current HTTP request struct which can be used to read request data. See http.Request for detailed documentation. Some notable methods and fields:
http.Request.Method, http.Request.PathValue, http.Request.URL, [http.Request.URL.Query], http.Request.Cookie, http.Request.Header, [http.Request.Header.Get].
Note that http.Request.ParseForm must be called before using http.Request.Form, http.Request.PostForm, and http.Request.PostValue.
type DotResp ¶ added in v0.5.0
DotResp is used as the .Resp field in buffered template invocations.
func (*DotResp) AddHeader ¶ added in v0.5.0
AddHeader adds a header field value, appending val to existing values for that field. It returns an empty string.
func (*DotResp) DelHeader ¶ added in v0.5.0
DelHeader deletes a header field. It returns an empty string.
func (*DotResp) ReturnStatus ¶ added in v0.5.0
ReturnStatus sets the HTTP response status and exits template rendering immediately.
func (*DotResp) ServeContent ¶ added in v0.5.0
ServeContent aborts execution of the template and instead responds to the request with content with any headers set by AddHeader and SetHeader so far but ignoring SetStatus.
type DotX ¶ added in v0.5.0
type DotX struct {
// contains filtered or unexported fields
}
DotX is used as the field at .X in all template invocations.
func (DotX) Func ¶ added in v0.5.0
Func returns a function by name to call manually. Can be used in combination with the call and try funcs.
func (DotX) StaticFileHash ¶ added in v0.5.0
StaticFileHash returns the sha-384 hash of the named asset file to be used for integrity or caching behavior.
type ErrorStatus ¶ added in v0.6.0
type ErrorStatus int
func (ErrorStatus) Error ¶ added in v0.6.0
func (e ErrorStatus) Error() string
type HandlerRoute ¶ added in v0.9.0
type HandlerRoute struct {
// Pattern uses net/http.ServeMux syntax (e.g. "POST /foo/{bar}").
Pattern string
Handler http.Handler
}
HandlerRoute pairs a ServeMux pattern with an http.Handler.
type Instance ¶ added in v0.4.0
type Instance struct {
// contains filtered or unexported fields
}
Instance is a configured, immutable, xtemplate request handler ready to execute templates and serve static files in response to http requests.
The only way to create a valid Instance is to call the Config.Instance method. Configuration of an Instance is intended to be immutable. Instead of mutating a running Instance, build a new Instance from a modified Config and swap them.
See also Server which manages instances and enables reloading them.
type InstanceRoute ¶ added in v0.4.0
type InstanceStats ¶ added in v0.4.0
type NatsConfig ¶ added in v0.8.0
type Option ¶ added in v0.6.0
func WithDir ¶ added in v0.8.0
WithDir creates an xtemplate.Option that can be used with xtemplate.Config.Server, xtemplate.Config.Instance, or xtemplate.Main to add an fs dot provider to the config.
func WithFuncMaps ¶ added in v0.3.0
func WithHandler ¶ added in v0.9.0
WithHandler adds a custom HTTP handler at pattern (net/http.ServeMux syntax, e.g. "POST /hook").
func WithLogger ¶ added in v0.3.0
func WithProvider ¶ added in v0.5.0
func WithTemplateFS ¶ added in v0.3.3
type ReturnError ¶
type ReturnError struct{}
ReturnError is a sentinel value that indicates a successful/normal exit but causes template execution to stop immediately. Used by funcs and dot field methods to perform custom actions.
func (ReturnError) Error ¶
func (ReturnError) Error() string
type Server ¶ added in v0.4.0
type Server struct {
// contains filtered or unexported fields
}
Server is a configured, *reloadable*, xtemplate request handler ready to execute templates and serve static files in response to http requests. It manages an Instance and allows you to reload template files with the same config by calling `server.Reload()`. If successful, Reload atomically swaps the old Instance with the new Instance so subsequent requests are handled by the new instance, and any outstanding requests still being served by the old Instance can continue to completion. The old instance's Config.Ctx is also cancelled.
The only way to create a valid *Server is to call Config.Server.
func (*Server) Handler ¶ added in v0.4.0
Handler returns a `http.Handler` that always routes new requests to the current Instance.
func (*Server) Instance ¶ added in v0.4.0
Instance returns the current Instance. After calling Reload, previous calls to Instance may be stale.
func (*Server) Reload ¶ added in v0.4.0
Reload creates a new Instance from the config and swaps it with the current instance if successful, otherwise returns the error.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
git
Package git serves an xtemplate site from a git repository, reusing app's config loading machinery.
|
Package git serves an xtemplate site from a git repository, reusing app's config loading machinery. |
|
watchfs
watchfs reloads the server upon changes to the templates directory or other configured directories.
|
watchfs reloads the server upon changes to the templates directory or other configured directories. |
|
Basic xtemplate CLI package.
|
Basic xtemplate CLI package. |
|
git
command
Git-backed xtemplate CLI package.
|
Git-backed xtemplate CLI package. |
|
watchfs
command
The default xtemplate CLI package.
|
The default xtemplate CLI package. |
|
examples
|
|
|
dotprovider
command
Custom DotProvider example: the "repository pattern".
|
Custom DotProvider example: the "repository pattern". |
|
embedded
command
Embedded single-binary example: the templates dir is compiled into the binary via //go:embed, so this binary serves its templates with no templates dir on disk at runtime.
|
Embedded single-binary example: the templates dir is compiled into the binary via //go:embed, so this binary serves its templates with no templates dir on disk at runtime. |
|
internal
module
|
|
|
providers
|
|
|
nats
module
|
|
|
register
module
|
|
|
test
module
|