miya

package module
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Feb 18, 2026 License: MIT Imports: 22 Imported by: 0

README

Miya Engine

Go Reference Go Report Card Test Go Version

A high-performance Jinja2-compatible template engine implementation in Go.

Documentation | Go Reference

Features

  • Jinja2 Compatibility: Parse and render Jinja2 templates with familiar syntax
  • High Performance: Optimized for speed with template compilation, caching, and AST node pooling
  • Memory Efficient: Optional Release() method for returning pooled nodes to reduce GC pressure
  • Template Inheritance: Full support for extends, blocks, and includes
  • Rich Filter System: Built-in filters plus support for custom filters
  • Flexible Loading: Load templates from filesystem, memory, or embedded resources
  • Security: Auto-escaping enabled by default to prevent XSS
  • Developer Friendly: Clear error messages with line numbers and debugging support

Installation

go get github.com/zipreport/miya

Quick Start

package main

import (
    "fmt"
    "log"

    "github.com/zipreport/miya"
)

func main() {
    env := miya.NewEnvironment()

    tmpl, err := env.FromString("Hello {{ name }}!")
    if err != nil {
        log.Fatal(err)
    }

    ctx := miya.NewContext()
    ctx.Set("name", "World")

    output, err := tmpl.Render(ctx)
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println(output) // Output: Hello World!
}

Supported Features

Core Features
  • Variable substitution: {{ variable }}
  • Control structures: {% if %}, {% for %}, etc.
  • Template inheritance: {% extends %}, {% block %}
  • Includes: {% include %}
  • Macros: {% macro %}
  • Filters: {{ value|upper|trim }}
  • List/Dict comprehensions: {{ [x*2 for x in items] }}
  • Filter blocks: {% filter upper %}content{% endfilter %}
  • Do statements: {% do expression %}
  • Comments: {# comment #}
  • Whitespace control: {%- -%}
  • Custom delimiters
Built-in Filters
  • String: capitalize, lower, upper, title, trim, replace
  • HTML: escape, safe, urlencode
  • Collections: first, last, length, join, sort, reverse
  • Numbers: abs, round, int, float

Advanced Examples

List/Dict Comprehensions

Create collections with concise syntax:

template := `
Active users: {{ [user.name for user in users if user.active] }}
User lookup: {{ {user.id: user.name for user in users} }}
Cart total: ${{ [item.price * item.qty for item in cart]|sum }}
`

ctx := miya.NewContext()
ctx.Set("users", []map[string]interface{}{
    {"id": 1, "name": "Alice", "active": true},
    {"id": 2, "name": "Bob", "active": false},
    {"id": 3, "name": "Charlie", "active": true},
})
ctx.Set("cart", []map[string]interface{}{
    {"price": 10.99, "qty": 2},
    {"price": 5.50, "qty": 1},
})

result, _ := env.RenderString(template, ctx)
// Output: Active users: [Alice, Charlie]
//         User lookup: {1: Alice, 2: Bob, 3: Charlie}  
//         Cart total: $27.48
Filter Blocks

Apply filters to entire blocks of content:

template := `{% filter upper %}
Hello {{ name }}!
Your items:
{% for item in items %}
- {{ item }}
{% endfor %}
{% endfilter %}`

ctx := miya.NewContext()
ctx.Set("name", "Alice")
ctx.Set("items", []string{"apple", "banana"})

result, _ := env.RenderString(template, ctx)
// Output: HELLO ALICE!\nYOUR ITEMS:\n- APPLE\n- BANANA
Chained Filters
template := `{% filter trim|upper|reverse %}   hello world   {% endfilter %}`
result, _ := env.RenderString(template, ctx)
// Output: DLROW OLLEH
Do Statements

Execute expressions for side effects:

template := `{% do complex_calculation %}Result: {{ result }}`
Memory Management

Miya uses AST node pooling to reduce allocations during template parsing. For high-throughput applications, you can explicitly release pooled nodes when a template is no longer needed:

tmpl, _ := env.FromString("Hello {{ name }}!")
output, _ := tmpl.Render(ctx)

// Optional: release pooled AST nodes for reuse
tmpl.Release()

Note: Calling Release() is optional. If not called, nodes will be garbage collected normally. Use it in scenarios where you're creating many short-lived templates and want to minimize GC pressure.

Documentation

Full documentation is available at zipreport.github.io/miya.

More Examples

Check out the examples/ directory for comprehensive usage examples.

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

MIT License - see LICENSE for details.

Documentation

Index

Constants

View Source
const (
	ErrorTypeSyntax      = "SyntaxError"
	ErrorTypeUndefined   = "UndefinedError"
	ErrorTypeType        = "TypeError"
	ErrorTypeFilter      = "FilterError"
	ErrorTypeTest        = "TestError"
	ErrorTypeRuntime     = "RuntimeError"
	ErrorTypeTemplate    = "TemplateError"
	ErrorTypeInheritance = "InheritanceError"
	ErrorTypeMacro       = "MacroError"
)

ErrorType constants for different types of template errors

Variables

View Source
var ContextPool = sync.Pool{
	New: func() interface{} {
		return NewContext()
	},
}

ContextPool provides a pool of Context instances to reduce allocations

View Source
var FastStringBuilderPool = sync.Pool{
	New: func() interface{} {
		return NewFastStringBuilder(1024)
	},
}

FastStringBuilderPool provides pooled FastStringBuilder instances

View Source
var GlobalByteBufferPool = NewByteBufferPool()

Global byte buffer pool

View Source
var GlobalConcurrentCache = NewConcurrentCacheManager()

GlobalConcurrentCache is a global concurrent cache for template rendering

View Source
var GlobalConcurrentContextPool = NewConcurrentContextPool()

GlobalConcurrentContextPool is a global context pool for concurrent rendering

View Source
var GlobalEnvironmentRegistry = NewConcurrentEnvironmentRegistry()

GlobalEnvironmentRegistry is a global registry for concurrent environments

View Source
var GlobalErrorRecovery = NewErrorRecovery()

Global error recovery system

View Source
var GlobalMemoryProfiler = NewMemoryProfiler()

Global memory profiler

View Source
var GlobalPrecomputedHash = NewPrecomputedHash()

Global precomputed hash store

View Source
var GlobalSlicePool = &SlicePool{
	stringPool: sync.Pool{
		New: func() interface{} {
			return make([]string, 0, 16)
		},
	},
	intPool: sync.Pool{
		New: func() interface{} {
			return make([]int, 0, 16)
		},
	},
}
View Source
var GlobalSmallStringOptimizer = NewSmallStringOptimizer()

Global small string optimizer

View Source
var GlobalStringInterner = NewStringInterner()

Global string interner for template identifiers and common strings

View Source
var GlobalSyntaxErrorHelper = NewSyntaxErrorHelper()

Global syntax error helper

View Source
var GlobalTemplateDebugger = NewTemplateDebugger()

Global template debugger

View Source
var GlobalTemplateValidator = NewTemplateValidator()

Global template validator

View Source
var StringBuilderPool = sync.Pool{
	New: func() interface{} {
		return &strings.Builder{}
	},
}

StringBuilderPool provides a pool of strings.Builder instances to reduce allocations

Functions

func GetStringBuilder

func GetStringBuilder() *strings.Builder

GetStringBuilder gets a strings.Builder from the pool

func PutContext

func PutContext(ctx Context)

PutContext returns a Context to the pool

func PutFastStringBuilder

func PutFastStringBuilder(fsb *FastStringBuilder)

PutFastStringBuilder returns a FastStringBuilder to the pool

func PutStringBuilder

func PutStringBuilder(sb *strings.Builder)

PutStringBuilder returns a strings.Builder to the pool after resetting it

func RenderString

func RenderString(source string, context Context) (string, error)

RenderString is a convenience function using the default environment

func RenderTemplate

func RenderTemplate(name string, context Context) (string, error)

RenderTemplate is a convenience function using the default environment

func SetDefaultLoader

func SetDefaultLoader(loader Loader)

SetDefaultLoader sets the loader for the default environment

Types

type ByteBufferPool

type ByteBufferPool struct {
	// contains filtered or unexported fields
}

ByteBufferPool provides a pool of byte buffers for efficient string building

func NewByteBufferPool

func NewByteBufferPool() *ByteBufferPool

NewByteBufferPool creates a new byte buffer pool

func (*ByteBufferPool) Get

func (bbp *ByteBufferPool) Get() []byte

Get gets a byte buffer from the pool

func (*ByteBufferPool) Put

func (bbp *ByteBufferPool) Put(buf []byte)

Put returns a byte buffer to the pool

type CacheKey

type CacheKey struct {
	Template string
	Hash     uint64
}

CacheKey represents a cache key for templates

type CachedEnvironment

type CachedEnvironment struct {
	*Environment
	// contains filtered or unexported fields
}

CachedEnvironment wraps Environment with caching optimizations

func NewCachedEnvironment

func NewCachedEnvironment(opts ...EnvironmentOption) *CachedEnvironment

NewCachedEnvironment creates a cached environment

func (*CachedEnvironment) FromStringCached

func (ce *CachedEnvironment) FromStringCached(source string) (*Template, error)

FromStringCached compiles a template with caching

type CachedEnvironmentOptions

type CachedEnvironmentOptions struct {
	UseStringInterning bool
	ByteBufferPoolSize int
	ContextPoolSize    int
	TemplatePoolSize   int
}

CachedEnvironmentOptions provides options for memory optimization

func DefaultCachedOptions

func DefaultCachedOptions() *CachedEnvironmentOptions

DefaultCachedOptions returns default caching options

type CachedTemplate

type CachedTemplate struct {
	*Template
	// contains filtered or unexported fields
}

CachedTemplate wraps Template with caching optimizations

func NewCachedTemplate

func NewCachedTemplate(tmpl *Template) *CachedTemplate

NewCachedTemplate creates a new cached template wrapper

func (*CachedTemplate) RenderCached

func (ct *CachedTemplate) RenderCached(ctx Context) (string, error)

RenderCached renders the template with caching optimizations

type ConcurrentCacheManager

type ConcurrentCacheManager struct {
	// contains filtered or unexported fields
}

ConcurrentCacheManager provides thread-safe cache management

func NewConcurrentCacheManager

func NewConcurrentCacheManager() *ConcurrentCacheManager

NewConcurrentCacheManager creates a new concurrent cache manager

func (*ConcurrentCacheManager) Delete

func (ccm *ConcurrentCacheManager) Delete(key string)

Delete deletes a value from the cache

func (*ConcurrentCacheManager) Get

func (ccm *ConcurrentCacheManager) Get(key string) (interface{}, bool)

Get gets a value from the cache

func (*ConcurrentCacheManager) GetStats

func (ccm *ConcurrentCacheManager) GetStats() (hits, misses int64)

GetStats returns cache statistics

func (*ConcurrentCacheManager) Set

func (ccm *ConcurrentCacheManager) Set(key string, value interface{})

Set sets a value in the cache

type ConcurrentContextPool

type ConcurrentContextPool struct {
	// contains filtered or unexported fields
}

ConcurrentContextPool provides thread-safe context pooling

func NewConcurrentContextPool

func NewConcurrentContextPool() *ConcurrentContextPool

NewConcurrentContextPool creates a new concurrent context pool

func (*ConcurrentContextPool) Get

func (ccp *ConcurrentContextPool) Get() Context

Get gets a context from the pool

func (*ConcurrentContextPool) GetStats

func (ccp *ConcurrentContextPool) GetStats() (gets, puts int64)

GetStats returns pool statistics

func (*ConcurrentContextPool) Put

func (ccp *ConcurrentContextPool) Put(ctx Context)

Put returns a context to the pool

type ConcurrentEnvironmentRegistry

type ConcurrentEnvironmentRegistry struct {
	// contains filtered or unexported fields
}

ConcurrentEnvironmentRegistry manages multiple environments concurrently

func NewConcurrentEnvironmentRegistry

func NewConcurrentEnvironmentRegistry() *ConcurrentEnvironmentRegistry

NewConcurrentEnvironmentRegistry creates a new concurrent environment registry

func (*ConcurrentEnvironmentRegistry) GetDefaultEnvironment

func (cer *ConcurrentEnvironmentRegistry) GetDefaultEnvironment() *ThreadSafeEnvironment

GetDefaultEnvironment returns the default environment

func (*ConcurrentEnvironmentRegistry) GetEnvironment

func (cer *ConcurrentEnvironmentRegistry) GetEnvironment(name string) (*ThreadSafeEnvironment, bool)

GetEnvironment gets an environment by name

func (*ConcurrentEnvironmentRegistry) RegisterEnvironment

func (cer *ConcurrentEnvironmentRegistry) RegisterEnvironment(name string, env *ThreadSafeEnvironment)

RegisterEnvironment registers an environment with a name

type ConcurrentTemplateRenderer

type ConcurrentTemplateRenderer struct {
	// contains filtered or unexported fields
}

ConcurrentTemplateRenderer provides high-performance concurrent template rendering

func NewConcurrentTemplateRenderer

func NewConcurrentTemplateRenderer(template *Template, workers int) *ConcurrentTemplateRenderer

NewConcurrentTemplateRenderer creates a new concurrent template renderer

func (*ConcurrentTemplateRenderer) RenderAsync

func (ctr *ConcurrentTemplateRenderer) RenderAsync(ctx Context) <-chan renderResult

RenderAsync renders a template asynchronously

func (*ConcurrentTemplateRenderer) RenderBatch

func (ctr *ConcurrentTemplateRenderer) RenderBatch(contexts []Context) ([]string, []error)

RenderBatch renders multiple contexts in parallel

func (*ConcurrentTemplateRenderer) Start

func (ctr *ConcurrentTemplateRenderer) Start()

Start starts the concurrent renderer workers

func (*ConcurrentTemplateRenderer) Stop

func (ctr *ConcurrentTemplateRenderer) Stop()

Stop stops the concurrent renderer workers

type Context

type Context interface {
	Get(key string) (interface{}, bool)
	Set(key string, value interface{})
	Push() Context
	Pop() Context
	All() map[string]interface{}
	GetEnv() *Environment
	Clone() Context
}

func GetContext

func GetContext() Context

GetContext gets a Context from the pool

func NewCOWContext

func NewCOWContext() Context

NewCOWContext creates a new empty COW context

func NewCOWContextFrom

func NewCOWContextFrom(data map[string]interface{}) Context

NewCOWContextFrom creates a new COW context from a map

func NewContext

func NewContext() Context

func NewContextFrom

func NewContextFrom(data map[string]interface{}) Context

type ContextInterface

type ContextInterface interface {
	Get(key string) (interface{}, bool)
	Set(key string, value interface{})
	Push() ContextInterface
	Pop() ContextInterface
	All() map[string]interface{}
}

ContextInterface defines the shared context interface used across packages

type DebugEvent

type DebugEvent struct {
	Type         string
	TemplateName string
	Line         int
	Column       int
	Message      string
	Variables    map[string]interface{}
	Timestamp    time.Time
}

DebugEvent represents a debug event during template execution

type DebugInfo

type DebugInfo struct {
	Variables        map[string]interface{}
	AvailableFilters []string
	AvailableTests   []string
	TemplatePath     []string
	ExecutionTime    int64 // in nanoseconds
	MemoryUsage      int64 // in bytes
}

DebugInfo provides debugging information for templates

type DebugLevel

type DebugLevel int

DebugLevel represents the level of debug information

const (
	DebugLevelOff DebugLevel = iota
	DebugLevelBasic
	DebugLevelDetailed
	DebugLevelVerbose
)

type DebugTracer

type DebugTracer struct {
	// contains filtered or unexported fields
}

DebugTracer provides tracing capabilities for template execution

func NewDebugTracer

func NewDebugTracer() *DebugTracer

NewDebugTracer creates a new debug tracer

func (*DebugTracer) AddFilter

func (dt *DebugTracer) AddFilter(eventType string)

AddFilter adds an event type filter

func (*DebugTracer) Clear

func (dt *DebugTracer) Clear()

Clear clears all recorded events

func (*DebugTracer) Disable

func (dt *DebugTracer) Disable()

Disable disables debug tracing

func (*DebugTracer) Enable

func (dt *DebugTracer) Enable()

Enable enables debug tracing

func (*DebugTracer) GetDetailedLog

func (dt *DebugTracer) GetDetailedLog() string

GetDetailedLog returns a detailed log of all events

func (*DebugTracer) GetEvents

func (dt *DebugTracer) GetEvents() []DebugEvent

GetEvents returns all recorded events

func (*DebugTracer) GetSummary

func (dt *DebugTracer) GetSummary() string

GetSummary returns a summary of recorded events

func (*DebugTracer) RemoveFilter

func (dt *DebugTracer) RemoveFilter(eventType string)

RemoveFilter removes an event type filter

func (*DebugTracer) SetLevel

func (dt *DebugTracer) SetLevel(level DebugLevel)

SetLevel sets the debug level

func (*DebugTracer) TraceEvent

func (dt *DebugTracer) TraceEvent(eventType, templateName string, line, column int, message string, variables map[string]interface{})

TraceEvent records a debug event

type EnhancedTemplateError

type EnhancedTemplateError struct {
	Type         string
	Message      string
	TemplateName string
	Line         int
	Column       int
	Source       string
	Context      string
	Suggestion   string
	StackTrace   []StackFrame
}

EnhancedTemplateError represents an enhanced error that occurred during template processing

func NewEnhancedTemplateError

func NewEnhancedTemplateError(errorType, message, templateName string, line, column int) *EnhancedTemplateError

NewEnhancedTemplateError creates a new enhanced template error

func (*EnhancedTemplateError) DetailedError

func (te *EnhancedTemplateError) DetailedError() string

DetailedError returns a detailed error message with context

func (*EnhancedTemplateError) Error

func (te *EnhancedTemplateError) Error() string

Error implements the error interface

func (*EnhancedTemplateError) Unwrap

func (te *EnhancedTemplateError) Unwrap() error

Unwrap method for TemplateError compatibility

func (*EnhancedTemplateError) WithContext

func (te *EnhancedTemplateError) WithContext(context string) *EnhancedTemplateError

WithContext adds additional context to the error

func (*EnhancedTemplateError) WithSource

func (te *EnhancedTemplateError) WithSource(source string) *EnhancedTemplateError

WithSource adds source context to the error

func (*EnhancedTemplateError) WithStackFrame

func (te *EnhancedTemplateError) WithStackFrame(templateName string, line, column int, function string) *EnhancedTemplateError

WithStackFrame adds a stack frame to the error

func (*EnhancedTemplateError) WithSuggestion

func (te *EnhancedTemplateError) WithSuggestion(suggestion string) *EnhancedTemplateError

WithSuggestion adds a suggestion to fix the error

type Environment

type Environment struct {
	// contains filtered or unexported fields
}

func NewEnvironment

func NewEnvironment(opts ...EnvironmentOption) *Environment

func (*Environment) AddExtension

func (e *Environment) AddExtension(extension extensions.Extension) error

AddExtension registers an extension with the environment

func (*Environment) AddFilter

func (e *Environment) AddFilter(name string, filter interface{}) error

AddFilter adds a custom filter (for extensions and legacy support)

func (*Environment) AddFilterLegacy

func (e *Environment) AddFilterLegacy(name string, filter FilterFunc) error

func (*Environment) AddGlobal

func (e *Environment) AddGlobal(name string, value interface{})

func (*Environment) AddTest

func (e *Environment) AddTest(name string, test interface{}) error

AddTest adds a custom test (for extensions and legacy support)

func (*Environment) ApplyFilter

func (e *Environment) ApplyFilter(name string, value interface{}, args ...interface{}) (interface{}, error)

func (*Environment) ApplyTest

func (e *Environment) ApplyTest(name string, value interface{}, args ...interface{}) (bool, error)

ApplyTest applies a test to a value

func (*Environment) CallMacro

func (e *Environment) CallMacro(name string, ctx Context, args []interface{}, kwargs map[string]interface{}) (interface{}, error)

CallMacro calls a macro with the given arguments

func (*Environment) ClearCache

func (e *Environment) ClearCache()

ClearCache clears the template cache

func (*Environment) ClearInheritanceCache

func (e *Environment) ClearInheritanceCache()

ClearInheritanceCache clears all inheritance-related caches

func (*Environment) ClearMacros

func (e *Environment) ClearMacros()

ClearMacros clears all registered macros

func (*Environment) ConfigureInheritanceCache

func (e *Environment) ConfigureInheritanceCache(hierarchyTTL, resolvedTTL time.Duration, maxEntries int)

ConfigureInheritanceCache allows tuning of inheritance cache settings

func (*Environment) FromString

func (e *Environment) FromString(source string) (*Template, error)

func (*Environment) GetCacheSize

func (e *Environment) GetCacheSize() int

GetCacheSize returns the number of cached templates

func (*Environment) GetConfig

func (e *Environment) GetConfig(key string) (interface{}, bool)

GetConfig gets environment-level configuration for extensions

func (*Environment) GetExtension

func (e *Environment) GetExtension(name string) (extensions.Extension, bool)

ExtensionEnvironment interface implementation GetExtension retrieves another extension by name

func (*Environment) GetExtensionForTag

func (e *Environment) GetExtensionForTag(tagName string) (extensions.Extension, bool)

GetExtensionForTag returns the extension that handles the given tag

func (*Environment) GetExtensionRegistry

func (e *Environment) GetExtensionRegistry() *extensions.Registry

GetExtensionRegistry returns the extension registry

func (*Environment) GetFilter

func (e *Environment) GetFilter(name string) (FilterFunc, bool)

func (*Environment) GetInheritanceCacheStats

func (e *Environment) GetInheritanceCacheStats() runtime.CacheStats

GetInheritanceCacheStats returns inheritance cache performance statistics

func (*Environment) GetLoader

func (e *Environment) GetLoader() Loader

GetLoader returns the current template loader

func (*Environment) GetMacro

func (e *Environment) GetMacro(name string) (*macros.Macro, bool)

GetMacro retrieves a macro by name

func (*Environment) GetTemplate

func (e *Environment) GetTemplate(name string) (*Template, error)

func (*Environment) GetTest

func (e *Environment) GetTest(name string) (branching.TestFunc, bool)

GetTest retrieves a test function by name

func (*Environment) InvalidateTemplate

func (e *Environment) InvalidateTemplate(templateName string)

InvalidateTemplate removes template from both regular and inheritance caches

func (*Environment) IsCustomTag

func (e *Environment) IsCustomTag(tagName string) bool

IsCustomTag returns true if the tag is handled by an extension

func (*Environment) ListFilters

func (e *Environment) ListFilters() []string

ListFilters returns all available filter names

func (*Environment) ListMacros

func (e *Environment) ListMacros() []string

ListMacros returns all available macro names

func (*Environment) ListTemplates

func (e *Environment) ListTemplates() ([]string, error)

ListTemplates returns all available template names from the loader

func (*Environment) ListTests

func (e *Environment) ListTests() []string

ListTests returns all available test names

func (*Environment) RenderString

func (e *Environment) RenderString(source string, context Context) (string, error)

RenderString is a convenience method to compile and render a template from string

func (*Environment) RenderTemplate

func (e *Environment) RenderTemplate(name string, context Context) (string, error)

RenderTemplate is a convenience method to load and render a template by name

func (*Environment) SetCommentDelimiters

func (e *Environment) SetCommentDelimiters(start, end string)

func (*Environment) SetConfig

func (e *Environment) SetConfig(key string, value interface{})

SetConfig sets environment-level configuration for extensions

func (*Environment) SetDelimiters

func (e *Environment) SetDelimiters(varStart, varEnd, blockStart, blockEnd string)

func (*Environment) SetLoader

func (e *Environment) SetLoader(loader Loader)

type EnvironmentOption

type EnvironmentOption func(*Environment)

func WithAutoEscape

func WithAutoEscape(enabled bool) EnvironmentOption

func WithDebugUndefined

func WithDebugUndefined(enabled bool) EnvironmentOption

WithDebugUndefined enables debug undefined variable handling

func WithKeepTrailingNewline

func WithKeepTrailingNewline(enabled bool) EnvironmentOption

func WithLoader

func WithLoader(loader Loader) EnvironmentOption

func WithLstripBlocks

func WithLstripBlocks(enabled bool) EnvironmentOption

func WithStrictUndefined

func WithStrictUndefined(enabled bool) EnvironmentOption

WithStrictUndefined enables strict undefined variable handling

func WithTrimBlocks

func WithTrimBlocks(enabled bool) EnvironmentOption

func WithUndefinedBehavior

func WithUndefinedBehavior(behavior runtime.UndefinedBehavior) EnvironmentOption

WithUndefinedBehavior sets the undefined variable behavior

type ErrorHandler

type ErrorHandler struct {
	ShowSourceContext bool
	ShowStackTrace    bool
	ShowSuggestions   bool
	MaxSourceLines    int
}

ErrorHandler provides configurable error handling

func DefaultErrorHandler

func DefaultErrorHandler() *ErrorHandler

DefaultErrorHandler returns a default error handler

func (*ErrorHandler) FormatError

func (eh *ErrorHandler) FormatError(err error) string

FormatError formats an error according to the handler configuration

type ErrorRecovery

type ErrorRecovery struct {
	// contains filtered or unexported fields
}

ErrorRecovery provides error recovery capabilities

func NewErrorRecovery

func NewErrorRecovery() *ErrorRecovery

NewErrorRecovery creates a new error recovery system

func (*ErrorRecovery) AddDefaultStrategies

func (er *ErrorRecovery) AddDefaultStrategies()

AddDefaultStrategies adds default recovery strategies

func (*ErrorRecovery) AddStrategy

func (er *ErrorRecovery) AddStrategy(errorType string, strategy RecoveryStrategy)

AddStrategy adds a recovery strategy

func (*ErrorRecovery) Recover

func (er *ErrorRecovery) Recover(err *EnhancedTemplateError, ctx Context) (string, error)

Recover attempts to recover from an error

type FastStringBuilder

type FastStringBuilder struct {
	// contains filtered or unexported fields
}

FastStringBuilder is an optimized string builder for template rendering

func GetFastStringBuilder

func GetFastStringBuilder() *FastStringBuilder

GetFastStringBuilder gets a FastStringBuilder from the pool

func NewFastStringBuilder

func NewFastStringBuilder(capacity int) *FastStringBuilder

NewFastStringBuilder creates a new fast string builder

func (*FastStringBuilder) Len

func (fsb *FastStringBuilder) Len() int

Len returns the current length

func (*FastStringBuilder) Reset

func (fsb *FastStringBuilder) Reset()

Reset clears the buffer

func (*FastStringBuilder) String

func (fsb *FastStringBuilder) String() string

String returns the accumulated string

func (*FastStringBuilder) WriteByte

func (fsb *FastStringBuilder) WriteByte(b byte) error

WriteByte appends a byte to the buffer

func (*FastStringBuilder) WriteString

func (fsb *FastStringBuilder) WriteString(s string)

WriteString appends a string to the buffer

type FilterFunc

type FilterFunc func(value interface{}, args ...interface{}) (interface{}, error)

type InteractiveDebugger

type InteractiveDebugger struct {
	// contains filtered or unexported fields
}

InteractiveDebugger provides interactive debugging capabilities

func NewInteractiveDebugger

func NewInteractiveDebugger() *InteractiveDebugger

NewInteractiveDebugger creates a new interactive debugger

func (*InteractiveDebugger) Disable

func (id *InteractiveDebugger) Disable()

Disable disables the interactive debugger

func (*InteractiveDebugger) Enable

func (id *InteractiveDebugger) Enable()

Enable enables the interactive debugger

func (*InteractiveDebugger) GetWatchedValues

func (id *InteractiveDebugger) GetWatchedValues(ctx Context) map[string]interface{}

GetWatchedValues returns the values of watched variables

func (*InteractiveDebugger) RemoveBreakpoint

func (id *InteractiveDebugger) RemoveBreakpoint(templateName string, line int)

RemoveBreakpoint removes a breakpoint

func (*InteractiveDebugger) SetBreakpoint

func (id *InteractiveDebugger) SetBreakpoint(templateName string, line int)

SetBreakpoint sets a breakpoint at the specified line

func (*InteractiveDebugger) ShouldBreak

func (id *InteractiveDebugger) ShouldBreak(templateName string, line int) bool

ShouldBreak returns true if execution should break at this location

func (*InteractiveDebugger) Watch

func (id *InteractiveDebugger) Watch(varName string)

Watch adds a variable to watch

type Loader

type Loader = loader.Loader

type LoopInfo

type LoopInfo struct {
	Index     int
	Index0    int
	RevIndex  int
	RevIndex0 int
	First     bool
	Last      bool
	Length    int
}

type MemoryEfficientTemplate

type MemoryEfficientTemplate struct {
	*Template
	// contains filtered or unexported fields
}

MemoryEfficientTemplate provides memory-optimized template operations

func NewMemoryEfficientTemplate

func NewMemoryEfficientTemplate(tmpl *Template) *MemoryEfficientTemplate

NewMemoryEfficientTemplate creates a memory-efficient template wrapper

func (*MemoryEfficientTemplate) RenderMemoryEfficient

func (met *MemoryEfficientTemplate) RenderMemoryEfficient(ctx Context) (string, error)

RenderMemoryEfficient renders the template with memory optimizations

type MemoryOptimizedContext

type MemoryOptimizedContext struct {
	// contains filtered or unexported fields
}

MemoryOptimizedContext is a context implementation optimized for memory usage

func NewMemoryOptimizedContext

func NewMemoryOptimizedContext() *MemoryOptimizedContext

NewMemoryOptimizedContext creates a new memory-optimized context

func (*MemoryOptimizedContext) All

func (moc *MemoryOptimizedContext) All() map[string]interface{}

All returns all variables

func (*MemoryOptimizedContext) Clone

func (moc *MemoryOptimizedContext) Clone() Context

Clone creates a copy of the context

func (*MemoryOptimizedContext) Get

func (moc *MemoryOptimizedContext) Get(key string) (interface{}, bool)

Get retrieves a variable value

func (*MemoryOptimizedContext) GetEnv

func (moc *MemoryOptimizedContext) GetEnv() *Environment

GetEnv returns the environment (placeholder implementation)

func (*MemoryOptimizedContext) Pop

func (moc *MemoryOptimizedContext) Pop() Context

Pop returns to parent scope

func (*MemoryOptimizedContext) Push

func (moc *MemoryOptimizedContext) Push() Context

Push creates a new scope

func (*MemoryOptimizedContext) Set

func (moc *MemoryOptimizedContext) Set(key string, value interface{})

Set sets a variable value

type MemoryProfiler

type MemoryProfiler struct {
	// contains filtered or unexported fields
}

MemoryProfiler provides memory profiling capabilities

func NewMemoryProfiler

func NewMemoryProfiler() *MemoryProfiler

NewMemoryProfiler creates a new memory profiler

func (*MemoryProfiler) GetStats

func (mp *MemoryProfiler) GetStats() map[string]int64

GetStats returns memory profiling statistics

func (*MemoryProfiler) RecordAllocation

func (mp *MemoryProfiler) RecordAllocation(category string, size int64)

RecordAllocation records a memory allocation

func (*MemoryProfiler) RecordDeallocation

func (mp *MemoryProfiler) RecordDeallocation(category string, size int64)

RecordDeallocation records a memory deallocation

type MemoryStats

type MemoryStats struct {
	InternedStrings      int
	PooledContexts       int
	PooledTemplates      int
	PooledStringBuilders int
	PooledByteBuffers    int
}

MemoryStats provides memory usage statistics

func GetMemoryStats

func GetMemoryStats() *MemoryStats

GetMemoryStats returns current memory optimization statistics

type Namespace

type Namespace struct {
	// contains filtered or unexported fields
}

Namespace represents a Jinja2 namespace object Namespaces are mutable objects that allow sharing data between scopes

func NewNamespace

func NewNamespace() *Namespace

NewNamespace creates a new namespace object

func (*Namespace) All

func (ns *Namespace) All() map[string]interface{}

All returns a copy of all data in the namespace

func (*Namespace) Clear

func (ns *Namespace) Clear()

Clear removes all data from the namespace

func (*Namespace) Delete

func (ns *Namespace) Delete(key string)

Delete removes a key from the namespace

func (*Namespace) Get

func (ns *Namespace) Get(key string) (interface{}, bool)

Get retrieves a value from the namespace

func (*Namespace) Has

func (ns *Namespace) Has(key string) bool

Has checks if a key exists in the namespace

func (*Namespace) Set

func (ns *Namespace) Set(key string, value interface{})

Set sets a value in the namespace

func (*Namespace) String

func (ns *Namespace) String() string

String returns a string representation of the namespace

type NamespaceWrapper

type NamespaceWrapper struct {
	*Namespace
}

NamespaceWrapper wraps a namespace to provide dot-notation access in templates

func (*NamespaceWrapper) GetAttr

func (nw *NamespaceWrapper) GetAttr(name string) (interface{}, error)

GetAttr provides attribute-style access to namespace values

func (*NamespaceWrapper) SetAttr

func (nw *NamespaceWrapper) SetAttr(name string, value interface{}) error

SetAttr provides attribute-style setting of namespace values

type Node

type Node interface {
	// Will be expanded when we implement the parser
	String() string
}

type PerformanceMeasurement

type PerformanceMeasurement struct {
	Count     int64
	TotalTime time.Duration
	MinTime   time.Duration
	MaxTime   time.Duration
}

PerformanceMeasurement represents a performance measurement

type PerformanceProfiler

type PerformanceProfiler struct {
	// contains filtered or unexported fields
}

PerformanceProfiler provides performance profiling capabilities

func NewPerformanceProfiler

func NewPerformanceProfiler() *PerformanceProfiler

NewPerformanceProfiler creates a new performance profiler

func (*PerformanceProfiler) Clear

func (pp *PerformanceProfiler) Clear()

Clear clears all measurements

func (*PerformanceProfiler) Disable

func (pp *PerformanceProfiler) Disable()

Disable disables performance profiling

func (*PerformanceProfiler) Enable

func (pp *PerformanceProfiler) Enable()

Enable enables performance profiling

func (*PerformanceProfiler) GetMeasurements

func (pp *PerformanceProfiler) GetMeasurements() map[string]*PerformanceMeasurement

GetMeasurements returns all performance measurements

func (*PerformanceProfiler) GetReport

func (pp *PerformanceProfiler) GetReport() string

GetReport returns a performance report

func (*PerformanceProfiler) StartMeasurement

func (pp *PerformanceProfiler) StartMeasurement(operation string) func()

StartMeasurement starts measuring performance for a given operation

type PrecomputedHash

type PrecomputedHash struct {
	// contains filtered or unexported fields
}

PrecomputedHash stores precomputed hash values to avoid recomputation

func NewPrecomputedHash

func NewPrecomputedHash() *PrecomputedHash

NewPrecomputedHash creates a new precomputed hash store

func (*PrecomputedHash) GetHash

func (ph *PrecomputedHash) GetHash(s string) uint64

GetHash gets or computes a hash for a string

type RateLimitedRenderer

type RateLimitedRenderer struct {
	// contains filtered or unexported fields
}

RateLimitedRenderer provides rate-limited template rendering

func NewRateLimitedRenderer

func NewRateLimitedRenderer(template *Template, maxConcurrent int) *RateLimitedRenderer

NewRateLimitedRenderer creates a new rate-limited renderer

func (*RateLimitedRenderer) Render

func (rlr *RateLimitedRenderer) Render(ctx Context) (string, error)

Render renders the template with rate limiting

type RecoveryStrategy

type RecoveryStrategy func(err *EnhancedTemplateError, ctx Context) (string, error)

RecoveryStrategy represents an error recovery strategy

type RuntimeError

type RuntimeError struct {
	*EnhancedTemplateError
	Stack []string
}

RuntimeError creates a runtime error (wrapper around EnhancedTemplateError)

func NewRuntimeError

func NewRuntimeError(template string, line, column int, format string, args ...interface{}) *RuntimeError

NewRuntimeError creates a new runtime error (enhanced version)

func (*RuntimeError) Error

func (e *RuntimeError) Error() string

Error method for RuntimeError to include stack trace

type SlicePool

type SlicePool struct {
	// contains filtered or unexported fields
}

SlicePool provides pools for commonly used slice types

func (*SlicePool) GetIntSlice

func (sp *SlicePool) GetIntSlice() []int

GetIntSlice gets an int slice from the pool

func (*SlicePool) GetStringSlice

func (sp *SlicePool) GetStringSlice() []string

GetStringSlice gets a string slice from the pool

func (*SlicePool) PutIntSlice

func (sp *SlicePool) PutIntSlice(slice []int)

PutIntSlice returns an int slice to the pool

func (*SlicePool) PutStringSlice

func (sp *SlicePool) PutStringSlice(slice []string)

PutStringSlice returns a string slice to the pool

type SmallStringOptimizer

type SmallStringOptimizer struct {
	// contains filtered or unexported fields
}

SmallStringOptimizer optimizes storage of small strings

func NewSmallStringOptimizer

func NewSmallStringOptimizer() *SmallStringOptimizer

NewSmallStringOptimizer creates a new small string optimizer

func (*SmallStringOptimizer) OptimizeString

func (sso *SmallStringOptimizer) OptimizeString(s string) string

OptimizeString optimizes string storage for small strings

type StackFrame

type StackFrame struct {
	TemplateName string
	Line         int
	Column       int
	Function     string
	Source       string
}

StackFrame represents a frame in the template execution stack

type StringInterner

type StringInterner struct {
	// contains filtered or unexported fields
}

StringInterner provides string interning to reduce memory usage

func NewStringInterner

func NewStringInterner() *StringInterner

NewStringInterner creates a new string interner

func (*StringInterner) Clear

func (si *StringInterner) Clear()

Clear clears all interned strings

func (*StringInterner) Intern

func (si *StringInterner) Intern(s string) string

Intern interns a string, returning the canonical instance

func (*StringInterner) Size

func (si *StringInterner) Size() int

Size returns the number of interned strings

type SyntaxError

type SyntaxError struct {
	*EnhancedTemplateError
}

SyntaxError creates a syntax error (wrapper around EnhancedTemplateError)

func NewSyntaxError

func NewSyntaxError(template string, line, column int, format string, args ...interface{}) *SyntaxError

NewSyntaxError creates a new syntax error (enhanced version)

type SyntaxErrorHelper

type SyntaxErrorHelper struct {
	// contains filtered or unexported fields
}

SyntaxErrorHelper provides helpful syntax error messages

func NewSyntaxErrorHelper

func NewSyntaxErrorHelper() *SyntaxErrorHelper

NewSyntaxErrorHelper creates a new syntax error helper

func (*SyntaxErrorHelper) GetSuggestion

func (seh *SyntaxErrorHelper) GetSuggestion(errorMessage string) string

GetSuggestion returns a suggestion for common syntax errors

type Template

type Template struct {
	// contains filtered or unexported fields
}

func FromString

func FromString(source string) (*Template, error)

FromString is a convenience function that uses the default environment

func GetTemplate

func GetTemplate(name string) (*Template, error)

GetTemplate is a convenience function that uses the default environment

func (*Template) AST

func (t *Template) AST() parser.Node

func (*Template) GetASTAsTemplateNode

func (t *Template) GetASTAsTemplateNode() *parser.TemplateNode

GetASTAsTemplateNode returns the AST as a TemplateNode for inheritance processing

func (*Template) Name

func (t *Template) Name() string

func (*Template) Release

func (t *Template) Release()

Release returns pooled AST nodes back to their pools for reuse. This should be called when a template is no longer needed and you want to reduce memory pressure. After calling Release(), the template should not be used for rendering.

Note: This is optional - if not called, nodes will be garbage collected normally. Use this when you're done with a template and want to enable immediate node reuse.

func (*Template) Render

func (t *Template) Render(context Context) (string, error)

func (*Template) RenderTo

func (t *Template) RenderTo(w io.Writer, context Context) error

func (*Template) SetAST

func (t *Template) SetAST(ast parser.Node)

func (*Template) Source

func (t *Template) Source() string

type TemplateCache

type TemplateCache struct {
	// contains filtered or unexported fields
}

TemplateCache is a thread-safe LRU cache for compiled templates

func NewTemplateCache

func NewTemplateCache(maxSize int) *TemplateCache

NewTemplateCache creates a new template cache

func (*TemplateCache) Get

func (tc *TemplateCache) Get(key string) (*Template, bool)

Get retrieves a template from the cache

func (*TemplateCache) Put

func (tc *TemplateCache) Put(key string, tmpl *Template)

Put stores a template in the cache

type TemplateContextAdapter

type TemplateContextAdapter struct {
	// contains filtered or unexported fields
}

TemplateContextAdapter adapts Context to runtime.Context interface

func NewTemplateContextAdapter

func NewTemplateContextAdapter(ctx Context, env *Environment) *TemplateContextAdapter

NewTemplateContextAdapter creates a new TemplateContextAdapter

func (*TemplateContextAdapter) All

func (a *TemplateContextAdapter) All() map[string]interface{}

func (*TemplateContextAdapter) ApplyFilter

func (a *TemplateContextAdapter) ApplyFilter(name string, value interface{}, args ...interface{}) (interface{}, error)

func (*TemplateContextAdapter) ApplyTest

func (a *TemplateContextAdapter) ApplyTest(name string, value interface{}, args ...interface{}) (bool, error)

func (*TemplateContextAdapter) Clone

func (*TemplateContextAdapter) GetVariable

func (a *TemplateContextAdapter) GetVariable(name string) (interface{}, bool)

func (*TemplateContextAdapter) IsAutoescapeEnabled

func (a *TemplateContextAdapter) IsAutoescapeEnabled() bool

IsAutoescapeEnabled returns the environment's autoescape setting

func (*TemplateContextAdapter) SetVariable

func (a *TemplateContextAdapter) SetVariable(name string, value interface{})

type TemplateDebugger

type TemplateDebugger struct {
	// contains filtered or unexported fields
}

TemplateDebugger provides debugging capabilities

func NewTemplateDebugger

func NewTemplateDebugger() *TemplateDebugger

NewTemplateDebugger creates a new template debugger

func (*TemplateDebugger) AddBreakpoint

func (td *TemplateDebugger) AddBreakpoint(templateName string, line int)

AddBreakpoint adds a breakpoint at the specified line

func (*TemplateDebugger) AddWatchVariable

func (td *TemplateDebugger) AddWatchVariable(varName string)

AddWatchVariable adds a variable to watch

func (*TemplateDebugger) Disable

func (td *TemplateDebugger) Disable()

Disable disables the debugger

func (*TemplateDebugger) Enable

func (td *TemplateDebugger) Enable()

Enable enables the debugger

func (*TemplateDebugger) GetWatchedVariables

func (td *TemplateDebugger) GetWatchedVariables(ctx Context) map[string]interface{}

GetWatchedVariables returns the values of watched variables

func (*TemplateDebugger) RemoveBreakpoint

func (td *TemplateDebugger) RemoveBreakpoint(templateName string, line int)

RemoveBreakpoint removes a breakpoint

func (*TemplateDebugger) ShouldBreak

func (td *TemplateDebugger) ShouldBreak(templateName string, line int) bool

ShouldBreak returns true if execution should break at this location

type TemplateError

type TemplateError = EnhancedTemplateError

TemplateError is an alias for EnhancedTemplateError for backward compatibility

func NewTemplateError

func NewTemplateError(template string, line, column int, format string, args ...interface{}) *TemplateError

NewTemplateError creates a new template error (enhanced version)

type TemplatePool

type TemplatePool struct {
	// contains filtered or unexported fields
}

TemplatePool provides a pool of template instances for concurrent rendering

func NewTemplatePool

func NewTemplatePool(template *Template) *TemplatePool

NewTemplatePool creates a new template pool

func (*TemplatePool) Get

func (tp *TemplatePool) Get() *Template

Get gets a template from the pool

func (*TemplatePool) Put

func (tp *TemplatePool) Put(tmpl *Template)

Put returns a template to the pool

func (*TemplatePool) RenderConcurrent

func (tp *TemplatePool) RenderConcurrent(ctx Context) (string, error)

RenderConcurrent renders using a pooled template

type TemplateValidator

type TemplateValidator struct {
	// contains filtered or unexported fields
}

TemplateValidator provides template validation capabilities

func NewTemplateValidator

func NewTemplateValidator() *TemplateValidator

NewTemplateValidator creates a new template validator

func (*TemplateValidator) AddDefaultRules

func (tv *TemplateValidator) AddDefaultRules()

AddDefaultRules adds default validation rules

func (*TemplateValidator) AddRule

func (tv *TemplateValidator) AddRule(rule ValidationRule)

AddRule adds a validation rule

func (*TemplateValidator) Validate

func (tv *TemplateValidator) Validate(templateName, source string) []*ValidationError

Validate validates a template

type TestFunc

type TestFunc func(value interface{}, args ...interface{}) (bool, error)

type ThreadSafeEnvironment

type ThreadSafeEnvironment struct {
	*Environment
	// contains filtered or unexported fields
}

ThreadSafeEnvironment provides thread-safe environment operations

func NewThreadSafeEnvironment

func NewThreadSafeEnvironment(opts ...EnvironmentOption) *ThreadSafeEnvironment

NewThreadSafeEnvironment creates a new thread-safe environment

func (*ThreadSafeEnvironment) AddFilterConcurrent

func (tse *ThreadSafeEnvironment) AddFilterConcurrent(name string, filter FilterFunc) error

AddFilterConcurrent adds a filter in a thread-safe manner

func (*ThreadSafeEnvironment) AddGlobalConcurrent

func (tse *ThreadSafeEnvironment) AddGlobalConcurrent(name string, value interface{})

AddGlobalConcurrent adds a global variable in a thread-safe manner

func (*ThreadSafeEnvironment) FromStringConcurrent

func (tse *ThreadSafeEnvironment) FromStringConcurrent(source string) (*ThreadSafeTemplate, error)

FromStringConcurrent compiles a template from string in a thread-safe manner

func (*ThreadSafeEnvironment) GetTemplateConcurrent

func (tse *ThreadSafeEnvironment) GetTemplateConcurrent(name string) (*ThreadSafeTemplate, error)

GetTemplateConcurrent retrieves a template in a thread-safe manner

type ThreadSafeTemplate

type ThreadSafeTemplate struct {
	*Template
	// contains filtered or unexported fields
}

ThreadSafeTemplate provides thread-safe template operations

func NewThreadSafeTemplate

func NewThreadSafeTemplate(tmpl *Template) *ThreadSafeTemplate

NewThreadSafeTemplate creates a new thread-safe template wrapper

func (*ThreadSafeTemplate) RenderConcurrent

func (tst *ThreadSafeTemplate) RenderConcurrent(ctx Context) (string, error)

RenderConcurrent renders the template in a thread-safe manner

type UndefinedError

type UndefinedError struct {
	*EnhancedTemplateError
	Variable string
}

UndefinedError creates an undefined variable error (wrapper around EnhancedTemplateError)

func NewUndefinedError

func NewUndefinedError(variable, template string, line, column int) *UndefinedError

NewUndefinedError creates a new undefined variable error (enhanced version)

func (*UndefinedError) Error

func (e *UndefinedError) Error() string

Error method for UndefinedError to provide specific undefined variable message

type ValidationError

type ValidationError struct {
	*EnhancedTemplateError
	Severity string // "error", "warning", "info"
}

ValidationError represents a template validation error

func NewValidationError

func NewValidationError(severity, message, templateName string, line, column int) *ValidationError

NewValidationError creates a new validation error

type ValidationRule

type ValidationRule struct {
	Name        string
	Description string
	Severity    string
	Check       func(templateName, source string) []*ValidationError
}

ValidationRule represents a validation rule

Jump to

Keyboard shortcuts

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