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.
Basic Usage
Section titled “Basic Usage”Include the entire contents of a file:
{{ snippet "../src/main.go" }}The path is relative to the template directory.
Named Snippets
Section titled “Named Snippets”Extract a specific section by marking it in the source file with comments:
Source file (src/handler.go)
Section titled “Source file (src/handler.go)”package main
// boilerplate-snippet: handlerfunc handleRequest(w http.ResponseWriter, r *http.Request) { w.Write([]byte("Hello, World!"))}// boilerplate-snippet: handler
// boilerplate-snippet: middlewarefunc 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: middlewareTemplate file
Section titled “Template file”Here's the request handler:
{{ snippet "../src/handler.go" "handler" }}
And the middleware:
{{ snippet "../src/handler.go" "middleware" }}Snippet Markers
Section titled “Snippet Markers”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)Use Case: Living Documentation
Section titled “Use Case: Living Documentation”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:
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.