http.handlers.templates
Template functions/actions are still experimental and subject to change.
Configuration
The root path from which to load files. Required if template functions accessing the file system are used (such as
include).Default is {http.vars.root} if set, or current working directory otherwise.The MIME types for which to render templates. Important to use this if the route matchers do not exclude images or other binary files.
The template action delimiters. Must be precisely two elements: the opening and closing delimiters.
Custom template functions registered as modules. These often act as components on web pages.Module namespace:
http.handlers.templates.functionsTemplate Context
The following data and functions are available to templates:Request Data
Arguments passed to this page/context, for example as the result of an
include.The current HTTP request object with fields:
.Method- The HTTP method.URL- The URL with component fields (Scheme, Host, Path, etc.).Header- The header fields.Host- The Host or :authority header
Like
.Req, except it accesses the original HTTP request before rewrites or other internal modifications.Returns the hostname portion (no port) of the Host header.
Returns the connection’s IP address.
Returns the real client’s IP address if
trusted_proxies was configured, otherwise returns the connection’s IP address.Response Manipulation
Adds a header field to the HTTP response.
Sets a header field on the HTTP response, replacing any existing value.
Deletes a header field on the HTTP response.
Template Functions
All Sprig functions are supported, plus Caddy-specific functions:Placeholders and Environment
Gets an environment variable.
Gets a placeholder variable. The braces (Short alias:
{}) must be omitted.phCookies
Gets the value of a cookie by name.
File Operations
Includes the contents of another file, rendering it in-place. Optionally pass key-value pairs as arguments to be accessed by the included file using
.Args.The contents are NOT escaped, so only include trusted template files.
Reads and returns the contents of another file, parsing it as a template and adding any template definitions to the template stack.If there are no definitions, the filepath will be the definition name. Any
{{ define }} blocks will be accessible by {{ template }} or {{ block }}.Imports must happen before the template or block action is called. The contents are NOT escaped.
Reads and returns the contents of another file, as-is.
The contents are NOT escaped, so only read trusted files.
Returns a list of files in the given directory, which is relative to the template context’s file root.
Returns true if the file exists.
HTTP Includes
Includes the contents of another file by making a virtual HTTP request (sub-request). The URI path must exist on the same virtual server.The request is crafted in memory and the handler is invoked directly for increased efficiency.
Content Processing
Splits front matter from the body. Front matter is metadata at the beginning of a file.Supported formats:
- YAML: Surrounded by
--- - TOML: Surrounded by
+++ - JSON: Surrounded by
{and}
.Meta- Metadata fields.Body- Body after front matter
Removes HTML from a string.
Formatting
Transforms size and time inputs to human readable format using go-humanize.Format types:
size- Turns bytes into “2.3 MB”time- Turns time string into “2 weeks ago”
time format, append :layout to specify custom time layout (default: RFC1123Z).Passes a string through
url.PathEscape, replacing characters that have special meaning in URL path parameters.Useful for including filenames containing ?, &, % in URL paths or as img src attributes.Error Handling
Returns an error with the given status code to the HTTP handler chain.
Experimental Functions
Invokes a custom template function only if it is registered (plugged-in) in the
http.handlers.templates.functions.* namespace.If the named function is not available, the invocation is ignored and a log message is emitted.EXPERIMENTAL: Subject to change or removal.
Configuration Examples
Basic Templates
Custom File Root
Custom Delimiters
Full Stack Example
Template Examples
Dynamic Navigation
Markdown Blog Post
Conditional Content
Include Header/Footer
Templates are executed after other response transformers in the handler chain. Place the
templates handler after encode so that templates execute on uncompressed content.