Skip to main content
The templates module is a middleware which executes response bodies as Go templates. The syntax is documented in the Go standard library’s text/template package. Module ID: http.handlers.templates
Template functions/actions are still experimental and subject to change.

Configuration

string
default:"{http.vars.root}"
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.
array of strings
default:"['text/html', 'text/plain', 'text/markdown']"
The MIME types for which to render templates. Important to use this if the route matchers do not exclude images or other binary files.
array of strings
default:"['{{', '}}']"
The template action delimiters. Must be precisely two elements: the opening and closing delimiters.
module map
Custom template functions registered as modules. These often act as components on web pages.Module namespace: http.handlers.templates.functions

Template Context

The following data and functions are available to templates:

Request Data

slice
Arguments passed to this page/context, for example as the result of an include.
*http.Request
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
http.Request
Like .Req, except it accesses the original HTTP request before rewrites or other internal modifications.
string
Returns the hostname portion (no port) of the Host header.
string
Returns the connection’s IP address.
string
Returns the real client’s IP address if trusted_proxies was configured, otherwise returns the connection’s IP address.

Response Manipulation

function
Adds a header field to the HTTP response.
function
Sets a header field on the HTTP response, replacing any existing value.
function
Deletes a header field on the HTTP response.

Template Functions

All Sprig functions are supported, plus Caddy-specific functions:

Placeholders and Environment

function
Gets an environment variable.
function
Gets a placeholder variable. The braces ({}) must be omitted.
Short alias: ph

Cookies

Gets the value of a cookie by name.

File Operations

function
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.
function
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.
function
Reads and returns the contents of another file, as-is.
The contents are NOT escaped, so only read trusted files.
function
Returns a list of files in the given directory, which is relative to the template context’s file root.
function
Returns true if the file exists.

HTTP Includes

function
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

function
Renders the given Markdown text as HTML using the Goldmark library (CommonMark compliant).Extensions enabled:
  • GitHub Flavored Markdown
  • Footnote
  • Syntax highlighting (via Chroma)
function
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 }
Returns object with:
  • .Meta - Metadata fields
  • .Body - Body after front matter
function
Removes HTML from a string.

Formatting

function
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”
For time format, append :layout to specify custom time layout (default: RFC1123Z).
function
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

function
Returns an error with the given status code to the HTTP handler chain.

Experimental Functions

function
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.