Documentation
¶
Overview ¶
Package template provides a Jinja2-compatible template engine using Gonja. It supports the vars.* namespace and custom filters for case transformation, inflection, and string operations.
Index ¶
- Variables
- func CreateFileSystemLoader(baseDir string) (loaders.Loader, error)
- func CreateMemoryLoaderFromMap(templates map[string]string) loaders.Loader
- func ExtractMetadata(content string) (metaRaw, bodyRaw string, err error)
- func NewExecuteError(template string, err error) error
- func NewParseError(template string, line, column int, err error) error
- func RegisterFilters(filters *exec.FilterSet) error
- func RegisterToFilter(filters *exec.FilterSet, reg *dialect.Registry) error
- type Action
- type Context
- type ContextBuilder
- type Engine
- func (e *Engine) CacheLen() int
- func (e *Engine) Environment() *exec.Environment
- func (e *Engine) ExecuteToString(content string, ctx Context) (string, error)
- func (e *Engine) MustParseString(content string) Template
- func (e *Engine) ParseFile(path string) (Template, error)
- func (e *Engine) ParseString(content string) (Template, error)
- func (e *Engine) ParseStringNamed(content, name string) (Template, error)
- func (e *Engine) RenderAndParseMetadata(metaRaw string, ctx Context) (*Metadata, error)
- func (e *Engine) SetLoader(loader loaders.Loader)
- func (e *Engine) SetSharedContent(content map[string]string)
- type Metadata
- type MetadataParser
- type Option
- type Template
- type TemplateError
- type TemplateExecutor
- type TemplateRenderer
Constants ¶
This section is empty.
Variables ¶
var ( // ErrParse indicates a template parsing error. ErrParse = errors.New("template parse error") // ErrExecute indicates a template execution error. ErrExecute = errors.New("template execution error") )
Common sentinel errors for the template package.
var ( ErrNoMetadataBlock = errors.New("no metadata block found") ErrMalformedMetadata = errors.New("malformed metadata line") ErrInvalidBoolValue = errors.New("invalid boolean value") ErrConflictingAction = errors.New("conflicting action: cannot have both append and inject") ErrConflictingOpenAPIAction = errors.New("conflicting action: openapi cannot be combined with append or inject") ErrMissingInjection = errors.New("inject action requires before or after clause") ErrMissingToField = errors.New("missing required 'to' field in metadata") ErrEmptyInjectMatcher = errors.New("inject clause requires non-empty matcher value") ErrOrphanInjectClause = errors.New("before/after clause without inject: true is ignored") )
Metadata extraction and parsing errors.
Functions ¶
func CreateFileSystemLoader ¶
CreateFileSystemLoader creates a Gonja FileSystemLoader for the given directory. This is the recommended way to set up template loading for Gonja.
func CreateMemoryLoaderFromMap ¶
CreateMemoryLoaderFromMap creates a Gonja MemoryLoader from a map of template contents. The keys should be template names (paths), values are template contents. This is useful for loading shared templates into memory.
func ExtractMetadata ¶
ExtractMetadata splits a template into its metadata block and body. The metadata block is delimited by "---" markers at the start of the template. Returns the raw metadata string, the template body, and any error.
Example:
--- to: output/file.go inject: true --- template body here
func NewExecuteError ¶
NewExecuteError creates a new execution error with context.
func NewParseError ¶
NewParseError creates a new parse error with context.
func RegisterFilters ¶
RegisterFilters registers all custom filters with the given filter set. Returns an error if any filter fails to register.
Types ¶
type Context ¶
Context represents the template execution context. It provides data to templates through multiple namespaces.
type ContextBuilder ¶
type ContextBuilder struct {
// contains filtered or unexported fields
}
ContextBuilder provides a fluent API for constructing template contexts. It supports both scaffold and generate context shapes.
func NewContextBuilder ¶
func NewContextBuilder() *ContextBuilder
NewContextBuilder creates a new ContextBuilder.
func (*ContextBuilder) Build ¶
func (b *ContextBuilder) Build() Context
Build returns the constructed context.
func (*ContextBuilder) WithName ¶
func (b *ContextBuilder) WithName(name string) *ContextBuilder
WithName adds the "name" key and "n" namespace with pre-computed name variants.
func (*ContextBuilder) WithVars ¶
func (b *ContextBuilder) WithVars(vars map[string]any) *ContextBuilder
WithVars adds the "vars" namespace.
type Engine ¶
type Engine struct {
// contains filtered or unexported fields
}
Engine wraps Gonja to provide a consistent template interface.
func NewEngine ¶
NewEngine creates a new template engine with the given options. Returns an error if the engine cannot be initialized.
func (*Engine) CacheLen ¶
CacheLen returns the number of templates currently in the cache. This is intended for testing and diagnostics.
func (*Engine) Environment ¶
func (e *Engine) Environment() *exec.Environment
Environment returns the underlying Gonja environment. This can be used for advanced customization.
func (*Engine) ExecuteToString ¶
ExecuteToString is a convenience method that parses and executes a template.
func (*Engine) MustParseString ¶
MustParseString parses a template from a string and panics on error. This is useful for templates that are known to be valid at compile time.
func (*Engine) ParseString ¶
ParseString parses a template from a string.
func (*Engine) ParseStringNamed ¶
ParseStringNamed parses a template from a string with a given name. The name is used for error reporting.
func (*Engine) RenderAndParseMetadata ¶
RenderAndParseMetadata renders the raw metadata using the template engine, then parses the result into a Metadata struct. This is a convenience function that combines rendering and parsing.
func (*Engine) SetLoader ¶
SetLoader sets a custom loader for template resolution (used by ParseFile).
func (*Engine) SetSharedContent ¶
SetSharedContent stores raw shared template content so that {% include %} directives in string-parsed templates can resolve them. Keys are normalised to basenames so that {% include "header.tmpl" %} resolves regardless of the original filesystem path.
type Metadata ¶
type Metadata struct {
To string // Output file path
Action Action // File operation: Create, Append, Inject, or OpenAPI
InjectClause types.InjectClause // Before or After (for inject action)
InjectMatcher string // The marker string to match for injection
Notes string // Optional notes to display after generation
Description string // Optional description for generator listing
Validate bool // Run OpenAPI validation after merge (openapi action only)
Extra map[string]string // Additional key-value pairs from metadata
}
Metadata represents the parsed metadata from a template's --- block.
func ParseMetadata ¶
ParseMetadata parses rendered metadata lines into a Metadata struct. The input should be the metadata content after template rendering. Each line should be in "key: value" format.
type MetadataParser ¶
type MetadataParser interface {
RenderAndParseMetadata(metaRaw string, ctx Context) (*Metadata, error)
}
MetadataParser handles legacy metadata block extraction.
type Option ¶
type Option func(*Engine)
Option configures the template engine.
func WithDialectRegistry ¶
WithDialectRegistry returns an Option that configures the engine with a dialect registry for the to() filter. The registry is immutable after engine creation.
type Template ¶
type Template interface {
// Execute renders the template with the given context.
Execute(ctx Context) (string, error)
}
Template represents a parsed template ready for execution.
type TemplateError ¶
type TemplateError struct {
// Op is the operation that failed (e.g., "parse", "execute").
Op string
// Template is the name or path of the template.
Template string
// Line is the line number where the error occurred (if available).
Line int
// Column is the column number where the error occurred (if available).
Column int
// Err is the underlying error.
Err error
}
TemplateError wraps template-related errors with additional context.
func (*TemplateError) Error ¶
func (e *TemplateError) Error() string
Error returns the formatted error message.
func (*TemplateError) Unwrap ¶
func (e *TemplateError) Unwrap() error
Unwrap returns the underlying error for errors.Is and errors.As.
type TemplateExecutor ¶
type TemplateExecutor interface {
TemplateRenderer
MetadataParser
}
TemplateExecutor combines rendering and metadata parsing capabilities.