tpl

package module
v1.0.10 Latest Latest
Warning

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

Go to latest
Published: Mar 28, 2025 License: MIT Imports: 36 Imported by: 0

README

GoDoc

Template Engine for Go

This is a legacy template engine system, made to be compatible with an older version initially written in PHP.

Features

  • Template syntax with interpolation and control structures
  • Support for custom filters and functions
  • Parallel template execution
  • Structured error handling with location information
  • Context-aware template execution

Recent Modernization

This codebase has been updated to use modern Go practices:

  • Added comprehensive documentation with GoDoc-compatible comments
  • Replaced interface{} with any type alias
  • Enhanced error handling with errors.Is() and errors.As() support
  • Added proper context cancellation handling
  • Implemented structured logging with log/slog
  • Improved concurrency patterns
  • Applied generics for type-safe operations

Usage

See the SYNTAX.md file for template syntax documentation.

package main

import (
	"context"
	"fmt"
	
	"github.com/KarpelesLab/tpl"
)

func main() {
	// Create a new template engine
	engine := tpl.New()
	
	// Add a template
	engine.Raw.TemplateData["main"] = "Hello {{name}}!"
	
	// Set up a context with variables
	ctx := context.Background()
	ctx = tpl.ValuesCtx(ctx, map[string]any{
		"name": "World",
	})
	
	// Compile templates
	if err := engine.Compile(ctx); err != nil {
		panic(err)
	}
	
	// Execute template
	result, err := engine.ParseAndReturn(ctx, "main")
	if err != nil {
		panic(err)
	}
	
	fmt.Println(result) // Output: Hello World!
}

License

This project is released under the MIT license.

Documentation

Overview

Package tpl provides a template engine with string interpolation and control structures.

Package tpl provides a template engine with string interpolation and control structures.

Package tpl provides a template engine with string interpolation and control structures.

Package tpl provides a template engine with string interpolation and control structures.

Index

Constants

This section is empty.

Variables

View Source
var BBCodeCompiler = bbcode.NewCompiler(true, true)
View Source
var (
	// ErrTplNotFound is returned when a requested template is not found.
	ErrTplNotFound = errors.New("tpl: Template not found")
)

Common template errors.

Functions

func AsOutValue

func AsOutValue(ctx context.Context, v interface{}) *interfaceValue

func CallFunction

func CallFunction(ctx context.Context, funcName string, params Values, target WritableValue) error

func CompareValues

func CompareValues(ctx context.Context, o1, o2 interface{}) (bool, error)

func FormatSize

func FormatSize(v uint64) string

FormatSize converts a size in bytes to a human-readable format using IEC units.

func LogDebug added in v1.0.9

func LogDebug(ctx context.Context, msg string, arg ...any)

LogDebug logs a debug message with source information.

func LogError added in v1.0.9

func LogError(ctx context.Context, err error, msg string, arg ...any)

LogError logs an error with context information. It's designed to be used with template execution errors.

func LogWarn

func LogWarn(ctx context.Context, msg string, arg ...any)

LogWarn logs a warning message using the logger from context if available, otherwise falls back to the default structured logger.

func QueryEscapeAny

func QueryEscapeAny(ctx context.Context, val interface{}) string

func RegisterFilter

func RegisterFilter(name string, f TplFiltCallback)

func RegisterFunction

func RegisterFunction(name string, f *TplFunction)

func ResetServerCtx

func ResetServerCtx(ctx context.Context)

func ResolveValueIndex

func ResolveValueIndex(ctx context.Context, v any, s string) (any, error)

func ServerCtx

func ServerCtx(request *http.Request) context.Context

func ValuesCtx

func ValuesCtx(parent context.Context, values map[string]interface{}) context.Context

func ValuesCtxAlways

func ValuesCtxAlways(parent context.Context, values map[string]interface{}) context.Context

Types

type ArrayAccessGet

type ArrayAccessGet interface {
	OffsetGet(context.Context, string) (Value, error)
}

ArrayAccessGet defines an interface for types that can retrieve a Value by string key.

type ArrayAccessGetAny added in v1.0.5

type ArrayAccessGetAny interface {
	OffsetGet(context.Context, string) (any, error)
}

ArrayAccessGetAny defines an interface for types that can retrieve any value by string key.

type CtxLog

type CtxLog interface {
	// LogWarn logs a warning message with the given arguments
	LogWarn(msg string, arg ...any)
}

CtxLog defines an interface for context-aware logging.

type Error

type Error struct {
	// Message describes the error
	Message string
	// Template is the name of the template where the error occurred
	Template string
	// Line is the line number where the error occurred
	Line int
	// Char is the character position where the error occurred
	Char int
	// Stack contains a stack trace, if available
	Stack []byte
	// Parent is the wrapped error, if any
	Parent error
}

Error is a template error, containing details such as where an error occurred in the template source and details on the actual error. It implements the error interface and supports error wrapping with Unwrap().

func (*Error) Error

func (e *Error) Error() string

Error returns a string representation of the error. This implements the error interface.

func (*Error) Is added in v1.0.9

func (e *Error) Is(target error) bool

Is allows for error comparison using errors.Is.

func (*Error) String

func (e *Error) String() string

String returns a formatted error message with location details.

func (*Error) Unwrap

func (e *Error) Unwrap() error

Unwrap returns the wrapped error, enabling compatibility with errors.Is and errors.As.

type Page

type Page struct {
	// Version will be populated on compile
	Version int
	// Raw contains the template source data
	Raw RawData

	// MaxProcess controls parallel execution of templates
	// 0 means unlimited concurrency, 1 means serial execution
	MaxProcess int
	// contains filtered or unexported fields
}

Page represents a template engine instance containing compiled templates.

func New

func New() *Page

New creates a new template engine instance. The returned Page is ready to have templates added to it and then compiled.

func (*Page) Compile

func (e *Page) Compile(ctx context.Context) error

Compile processes all raw templates and builds the internal representation. It returns an error if any template fails to compile.

func (*Page) Dump

func (e *Page) Dump(o io.Writer, lvl int)

func (*Page) GetMime

func (e *Page) GetMime() string

GetMime returns the MIME type for the page. The default value is "text/html" if not explicitly set. If a charset is specified, it will be appended to the MIME type.

func (*Page) GetProperty

func (e *Page) GetProperty(p string) string

GetProperty returns the value of a page property. Returns an empty string if the property doesn't exist.

func (*Page) HasTpl

func (e *Page) HasTpl(tpl string) bool

HasTpl returns true if the template exists in the compiled templates.

func (*Page) Parse

func (e *Page) Parse(ctx context.Context, tpl string, out *interfaceValue) error

Parse executes the named template in the given context, writing output to the provided interfaceValue. Returns ErrTplNotFound if the template doesn't exist.

func (*Page) ParseAndReturn

func (e *Page) ParseAndReturn(ctx context.Context, tpl string) (string, error)

ParseAndReturn executes the named template in the given context and returns the result as a string. Returns an empty string and ErrTplNotFound if the template doesn't exist.

func (*Page) ParseAndWrite

func (e *Page) ParseAndWrite(ctx context.Context, tpl string, out io.Writer) error

ParseAndWrite executes the named template in the given context, writing output to the provided io.Writer. Returns ErrTplNotFound if the template doesn't exist.

type RawData

type RawData struct {
	PageProperties map[string]string // typically Charset=UTF-8 Content_Type=text/html
	TemplateData   map[string]string // actual contents for templates, at least "main" should be there
}

RawData contains the raw (uncompiled) data for current template

func (*RawData) FromDir

func (res *RawData) FromDir(d ...string) error

func (*RawData) FromVfs

func (res *RawData) FromVfs(src fs.FS, d ...string) error

func (*RawData) FromZip

func (res *RawData) FromZip(z *zip.Reader, d ...string) error

func (*RawData) IsValid

func (r *RawData) IsValid() bool

type TplCtxValue

type TplCtxValue int

TplCtxValue is used as a context key for template-related values.

const (
	// TplCtxLog is the context key for logging interface
	TplCtxLog TplCtxValue = iota + 1
)

type TplFiltCallback

type TplFiltCallback func(ctx context.Context, params Values, in Value, out WritableValue) error

type TplFuncCallback

type TplFuncCallback func(ctx context.Context, params Values, out WritableValue) error

type TplFunction

type TplFunction struct {
	Method     TplFuncCallback
	CanCompile bool
}

type Value

type Value interface {
	ReadValue(ctx context.Context) (any, error)
	WithCtx(ctx context.Context) *ValueCtx
}

Value defines an interface for template values that can be read and contextualized.

func NewValue

func NewValue(v interface{}) Value

type ValueCtx

type ValueCtx struct {
	Value
	// contains filtered or unexported fields
}

ValueCtx wraps a Value with its associated context.

func NewValueCtx

func NewValueCtx(ctx context.Context, v Value) *ValueCtx

func (*ValueCtx) Bytes

func (v *ValueCtx) Bytes() []byte

func (*ValueCtx) BytesErr

func (v *ValueCtx) BytesErr() ([]byte, error)

func (*ValueCtx) IsString

func (v *ValueCtx) IsString() bool

IsString checks if the raw value is either a string, or an interface made to return a string

func (*ValueCtx) MarshalJSON

func (v *ValueCtx) MarshalJSON() ([]byte, error)

func (*ValueCtx) MatchValueType

func (v *ValueCtx) MatchValueType(t interface{}) (interface{}, error)

func (*ValueCtx) Raw

func (v *ValueCtx) Raw() (any, error)

Raw resolves the wrapped Value by repeatedly calling ReadValue until reaching a non-ValueReader. This allows for nested value resolution.

func (*ValueCtx) String

func (v *ValueCtx) String() string

func (*ValueCtx) StringErr

func (v *ValueCtx) StringErr() (string, error)

func (*ValueCtx) ToBool

func (v *ValueCtx) ToBool() bool

func (*ValueCtx) ToFloat

func (v *ValueCtx) ToFloat() (float64, bool)

func (*ValueCtx) ToInt

func (v *ValueCtx) ToInt() (int64, bool)

type ValueReader added in v1.0.2

type ValueReader interface {
	ReadValue(ctx context.Context) (any, error)
}

ValueReader defines an interface for types that can read a value in a given context.

type Values

type Values []Value

Values represents a slice of Value objects.

type WritableValue

type WritableValue interface {
	Value
	Printf(fmt string, arg ...any) (int, error)
	Write([]byte) (int, error)
	WriteValue(context.Context, any) error
}

WritableValue extends Value with methods for writing output.

func NewEmptyValue

func NewEmptyValue() WritableValue

Jump to

Keyboard shortcuts

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