Skip to content

Code Snippets

The snippet helper lets you include code from source files in your templates. This is particularly useful for documentation — your code examples stay in sync with actual source files.

Include the entire contents of a file:

{{ snippet "../src/main.go" }}

The path is relative to the template directory.

Extract a specific section by marking it in the source file with comments:

package main
// boilerplate-snippet: handler
func handleRequest(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello, World!"))
}
// boilerplate-snippet: handler
// boilerplate-snippet: middleware
func loggingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Printf("%s %s", r.Method, r.URL.Path)
next.ServeHTTP(w, r)
})
}
// boilerplate-snippet: middleware
Here's the request handler:
{{ snippet "../src/handler.go" "handler" }}
And the middleware:
{{ snippet "../src/handler.go" "middleware" }}

The marker format is a comment containing boilerplate-snippet: <name>:

// boilerplate-snippet: my-section (Go, JavaScript, C, etc.)
# boilerplate-snippet: my-section (Python, Ruby, YAML, etc.)
<!-- boilerplate-snippet: my-section --> (HTML, XML)

Combine snippet with Boilerplate to keep documentation examples always up-to-date:

## API Handler
The main handler processes incoming requests:
```go
{{ snippet "../src/api/handler.go" "main-handler" }}

Run the server:

Terminal window
go run cmd/server/main.go --port {{ .Port }}
Every time you regenerate the docs, the code examples reflect the current state of your source code.