template

package
v0.36.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 8, 2026 License: MIT Imports: 20 Imported by: 0

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

Constants

This section is empty.

Variables

View Source
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.

View Source
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

func CreateFileSystemLoader(baseDir string) (loaders.Loader, error)

CreateFileSystemLoader creates a Gonja FileSystemLoader for the given directory. This is the recommended way to set up template loading for Gonja.

func CreateMemoryLoaderFromMap

func CreateMemoryLoaderFromMap(templates map[string]string) loaders.Loader

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

func ExtractMetadata(content string) (metaRaw, bodyRaw string, err error)

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

func NewExecuteError(template string, err error) error

NewExecuteError creates a new execution error with context.

func NewParseError

func NewParseError(template string, line, column int, err error) error

NewParseError creates a new parse error with context.

func RegisterFilters

func RegisterFilters(filters *exec.FilterSet) error

RegisterFilters registers all custom filters with the given filter set. Returns an error if any filter fails to register.

func RegisterToFilter added in v0.36.0

func RegisterToFilter(filters *exec.FilterSet, reg *dialect.Registry) error

RegisterToFilter registers a unified "to" filter that handles the "openapi" dialect natively and delegates all other dialect names to the provided registry (if non-nil).

Types

type Action

type Action string

Action represents the type of file operation to perform.

const (
	ActionCreate  Action = "Create"
	ActionAppend  Action = "Append"
	ActionInject  Action = "Inject"
	ActionOpenAPI Action = "OpenAPI"
)

type Context

type Context map[string]any

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

func NewEngine(opts ...Option) (*Engine, error)

NewEngine creates a new template engine with the given options. Returns an error if the engine cannot be initialized.

func (*Engine) CacheLen

func (e *Engine) CacheLen() int

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

func (e *Engine) ExecuteToString(content string, ctx Context) (string, error)

ExecuteToString is a convenience method that parses and executes a template.

func (*Engine) MustParseString

func (e *Engine) MustParseString(content string) Template

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) ParseFile

func (e *Engine) ParseFile(path string) (Template, error)

ParseFile parses a template from a file.

func (*Engine) ParseString

func (e *Engine) ParseString(content string) (Template, error)

ParseString parses a template from a string.

func (*Engine) ParseStringNamed

func (e *Engine) ParseStringNamed(content, name string) (Template, error)

ParseStringNamed parses a template from a string with a given name. The name is used for error reporting.

func (*Engine) RenderAndParseMetadata

func (e *Engine) RenderAndParseMetadata(metaRaw string, ctx Context) (*Metadata, error)

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

func (e *Engine) SetLoader(loader loaders.Loader)

SetLoader sets a custom loader for template resolution (used by ParseFile).

func (*Engine) SetSharedContent

func (e *Engine) SetSharedContent(content map[string]string)

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

func ParseMetadata(rendered string) (*Metadata, error)

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.

func (*Metadata) IsOpenAPI added in v0.36.0

func (m *Metadata) IsOpenAPI() bool

IsOpenAPI returns true if this metadata specifies an OpenAPI merge action.

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

func WithDialectRegistry(reg *dialect.Registry) Option

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.

type TemplateRenderer

type TemplateRenderer interface {
	ParseString(content string) (Template, error)
	ParseStringNamed(content, name string) (Template, error)
	ExecuteToString(content string, ctx Context) (string, error)
}

TemplateRenderer handles template parsing and execution.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL