liquid

package
v0.0.0-...-9fa7a8e Latest Latest
Warning

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

Go to latest
Published: Nov 23, 2025 License: MIT Imports: 17 Imported by: 0

Documentation

Index

Constants

View Source
const Version = "5.10.0"

Version is the version number of the Liquid Go implementation. This MUST match the Ruby implementation version exactly.

Variables

View Source
var (
	// FilterSeparator is the regex pattern for filter separator (|)
	FilterSeparator = regexp.MustCompile(`\|`)

	// ArgumentSeparator is the character used to separate arguments
	ArgumentSeparator = ','

	// FilterArgumentSeparator is the character used to separate filter arguments
	FilterArgumentSeparator = ':'

	// VariableAttributeSeparator is the character used to separate variable attributes
	VariableAttributeSeparator = '.'

	// WhitespaceControl is the character used for whitespace control
	WhitespaceControl = '-'

	// TagStart is the regex pattern for tag start ({%)
	TagStart = regexp.MustCompile(`\{\%`)

	// TagEnd is the regex pattern for tag end (%})
	TagEnd = regexp.MustCompile(`\%\}`)

	// TagName is the regex pattern for tag names
	TagName = regexp.MustCompile(`#|\w+`)

	// VariableSignature is the regex pattern for variable signatures
	VariableSignature = regexp.MustCompile(`\(?[\w\-\.\[\]]\)?`)

	// VariableSegment is the regex pattern for variable segments
	VariableSegment = regexp.MustCompile(`[\w\-]`)

	// VariableStart is the regex pattern for variable start ({{)
	VariableStart = regexp.MustCompile(`\{\{`)

	// VariableEnd is the regex pattern for variable end (}})
	VariableEnd = regexp.MustCompile(`\}\}`)

	// VariableIncompleteEnd is the regex pattern for incomplete variable end
	VariableIncompleteEnd = regexp.MustCompile(`\}\}?`)

	// QuotedString is the regex pattern for quoted strings
	QuotedString = regexp.MustCompile(`"[^"]*"|'[^']*'`)

	// QuotedFragment is the regex pattern for quoted fragments
	QuotedFragment = regexp.MustCompile(`"[^"]*"|'[^']*'|(?:[^\s,\|'"]|"[^"]*"|'[^']*')+`)

	// TagAttributes is the regex pattern for tag attributes
	TagAttributes = regexp.MustCompile(`(\w[\w-]*)\s*\:\s*("[^"]*"|'[^']*'|(?:[^\s,\|'"]|"[^"]*"|'[^']*')+)`)

	// AnyStartingTag is the regex pattern for any starting tag
	AnyStartingTag = regexp.MustCompile(`\{\%|\{\{`)

	// PartialTemplateParser is the regex pattern for partial template parsing
	PartialTemplateParser = regexp.MustCompile(`(?s)\{\%.*?\%\}|\{\{.*?\}\}?`)

	// TemplateParser is the regex pattern for template parsing
	TemplateParser = regexp.MustCompile(`(?s)(\{\%.*?\%\}|\{\{.*?\}\}?|\{\%|\{\{)`)

	// VariableParser is the regex pattern for variable parsing
	// Note: Go regexp doesn't support atomic groups or recursion, so we use a simpler pattern
	// that matches brackets with content or word characters with optional question mark
	VariableParser = regexp.MustCompile(`\[[^\[\]]*\]|[\w\-]+\??`)
)

Const contains constants used throughout the Liquid package.

View Source
var (
	// EmptyHash is an empty map that can be reused
	EmptyHash = map[string]interface{}{}

	// EmptyArray is an empty slice that can be reused
	EmptyArray = []interface{}{}
)

Const contains empty constants similar to Ruby's frozen empty collections.

View Source
var (
	// DecimalRegex matches decimal numbers
	DecimalRegex = regexp.MustCompile(`^-?\d+\.\d+$`)

	// UnixTimestampRegex matches unix timestamps
	UnixTimestampRegex = regexp.MustCompile(`^\d+$`)
)
View Source
var (
	// DefaultLocalePath is the default path to the English locale file
	DefaultLocalePath = filepath.Join("liquid", "locales", "en.yml")
)
View Source
var GlobalUsage = &Usage{}

GlobalUsage is the global usage tracker.

View Source
var (
	// TemplateNameRegex validates template names (letters, numbers, underscore, slash)
	TemplateNameRegex = regexp.MustCompile(`^[^./][a-zA-Z0-9_/]+$`)
)

Functions

func GetInvokableMethods

func GetInvokableMethods(drop interface{}) []string

GetInvokableMethods returns a list of invokable methods for a drop.

func IncrementUsage

func IncrementUsage(name string)

IncrementUsage increments usage for the global tracker.

func Inspect

func Inspect(obj interface{}, seen map[uintptr]bool) string

Inspect returns a detailed string representation of an object.

func InvokeDropOn

func InvokeDropOn(drop interface{}, methodOrKey string) interface{}

InvokeDropOn invokes a method on any drop type. Optimization: Uses cached method lookups to avoid repeated reflection.

func IsInvokable

func IsInvokable(drop interface{}, methodName string) bool

IsInvokable checks if a method is invokable on a drop.

func LoadPartial

func LoadPartial(templateName string, context interface {
	Registers() *Registers
}, parseContext ParseContextInterface) (interface{}, error)

LoadPartial is a convenience function to load a partial.

func MarkupContext

func MarkupContext(markup string) string

MarkupContext returns a context string for markup.

func Parse

func Parse(markup string, ss *StringScanner, cache map[string]interface{}) interface{}

Parse parses a markup string into an expression value. Optimization: Uses global cache when local cache is nil for better performance across templates.

func ParseConditionExpression

func ParseConditionExpression(parseContext ParseContextInterface, markup string, safe bool) interface{}

ParseConditionExpression parses an expression for use in conditions.

func RaiseUnknownTag

func RaiseUnknownTag(tag, blockName, blockDelimiter string, parseContext ParseContextInterface) error

RaiseUnknownTag raises an error for an unknown tag.

func RangeLookupParse

func RangeLookupParse(startMarkup, endMarkup string, ss *StringScanner, cache map[string]interface{}) interface{}

RangeLookupParse parses start and end markups into a RangeLookup or range.

func ResetDeprecations

func ResetDeprecations()

ResetDeprecations clears all warned deprecations in the global instance (useful for testing).

func SafeParse

func SafeParse(parser *Parser, ss *StringScanner, cache map[string]interface{}) interface{}

SafeParse parses an expression from a parser.

func SliceCollection

func SliceCollection(collection interface{}, from int, to *int) []interface{}

SliceCollection slices a collection from index `from` to index `to` (exclusive). If `to` is nil, slices to the end.

func ToDate

func ToDate(obj interface{}) *time.Time

ToDate converts a value to a time.Time.

func ToInteger

func ToInteger(num interface{}) (int, error)

ToInteger converts a value to an integer. Optimization: Fast path for int type (most common case).

func ToLiquid

func ToLiquid(obj interface{}) interface{}

ToLiquid converts a value to its liquid representation. This is a helper function that checks if the value implements ToLiquidValue or returns the value as-is.

func ToLiquidValue

func ToLiquidValue(obj interface{}) interface{}

ToLiquidValue converts an object to its liquid representation.

func ToNumber

func ToNumber(obj interface{}) (interface{}, bool)

ToNumber converts a value to a number (int, int64, or float64).

func ToNumberValue

func ToNumberValue(obj interface{}) (float64, bool)

ToNumberValue converts to float64 for comparison.

func ToS

func ToS(obj interface{}, seen map[uintptr]bool) string

ToS converts an object to a string representation. Optimization: Fast path for common types to enable compiler inlining.

func ToString

func ToString(v interface{}, ctx *Context) string

ToString converts a value to string.

func Warn

func Warn(name, alternative string)

Warn issues a deprecation warning using the global deprecations instance.

Types

type ArgumentError

type ArgumentError struct {
	Err *Error
}

ArgumentError represents an argument error.

func NewArgumentError

func NewArgumentError(message string) *ArgumentError

NewArgumentError creates a new ArgumentError with the given message.

func (*ArgumentError) Error

func (e *ArgumentError) Error() string

type BlankFileSystem

type BlankFileSystem struct{}

BlankFileSystem is a file system that doesn't allow includes.

func (*BlankFileSystem) ReadTemplateFile

func (b *BlankFileSystem) ReadTemplateFile(_ string) (string, error)

ReadTemplateFile always returns an error for BlankFileSystem.

type Block

type Block struct {
	*Tag
	// contains filtered or unexported fields
}

Block represents a block tag (tag with a body).

func NewBlock

func NewBlock(tagName, markup string, parseContext ParseContextInterface) *Block

NewBlock creates a new block tag.

func ParseBlock

func ParseBlock(tagName, markup string, tokenizer *Tokenizer, parseContext ParseContextInterface) (*Block, error)

ParseBlock parses a block tag from tokenizer.

func (*Block) Blank

func (b *Block) Blank() bool

Blank returns true if the block is blank.

func (*Block) BlockDelimiter

func (b *Block) BlockDelimiter() string

BlockDelimiter returns the block delimiter (e.g., "endif" for "if").

func (*Block) BlockName

func (b *Block) BlockName() string

BlockName returns the block name.

func (*Block) Nodelist

func (b *Block) Nodelist() []interface{}

Nodelist returns the nodelist from the body.

func (*Block) Parse

func (b *Block) Parse(tokenizer *Tokenizer) error

Parse parses the block body.

func (*Block) RaiseTagNeverClosed

func (b *Block) RaiseTagNeverClosed() error

RaiseTagNeverClosed raises an error for a tag that was never closed.

func (*Block) Render

func (b *Block) Render(context TagContext) string

Render renders the block body.

func (*Block) RenderToOutputBuffer

func (b *Block) RenderToOutputBuffer(context TagContext, output *string)

RenderToOutputBuffer renders the block body to the output buffer. If the block has a custom Render method that returns a non-empty string, it uses that instead of rendering the body (for backwards compatibility). This matches Ruby's behavior where Block#render_to_output_buffer calls render if it's been overridden, otherwise renders the body.

func (*Block) SetBlockDelimiter

func (b *Block) SetBlockDelimiter(delimiter string)

SetBlockDelimiter sets the block delimiter.

func (*Block) UnknownTag

func (b *Block) UnknownTag(tagName, markup string, tokenizer *Tokenizer) error

UnknownTag handles unknown tags encountered during parsing.

type BlockBody

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

BlockBody represents a block body containing nodes (tags, variables, text).

func NewBlockBody

func NewBlockBody() *BlockBody

NewBlockBody creates a new BlockBody.

func (*BlockBody) Blank

func (bb *BlockBody) Blank() bool

Blank returns true if the block body is blank.

func (*BlockBody) Nodelist

func (bb *BlockBody) Nodelist() []interface{}

Nodelist returns the nodelist.

func (*BlockBody) Parse

func (bb *BlockBody) Parse(tokenizer *Tokenizer, parseContext ParseContextInterface, unknownTagHandler func(string, string) bool) error

Parse parses tokens into the block body.

func (*BlockBody) RemoveBlankStrings

func (bb *BlockBody) RemoveBlankStrings()

RemoveBlankStrings removes blank strings from the block body.

func (*BlockBody) Render

func (bb *BlockBody) Render(context TagContext) string

Render renders the block body.

func (*BlockBody) RenderToOutputBuffer

func (bb *BlockBody) RenderToOutputBuffer(context TagContext, output *string)

RenderToOutputBuffer renders the block body to the output buffer.

type BreakInterrupt

type BreakInterrupt struct {
	*Interrupt
}

BreakInterrupt is thrown whenever a {% break %} is called.

func NewBreakInterrupt

func NewBreakInterrupt() *BreakInterrupt

NewBreakInterrupt creates a new break interrupt.

type Condition

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

Condition represents a Liquid condition.

func NewCondition

func NewCondition(left interface{}, operator string, right interface{}) *Condition

NewCondition creates a new Condition.

func (*Condition) And

func (c *Condition) And(condition *Condition)

And chains this condition with another using AND.

func (*Condition) Attach

func (c *Condition) Attach(attachment interface{})

Attach attaches an attachment to this condition.

func (*Condition) Attachment

func (c *Condition) Attachment() interface{}

Attachment returns the attachment.

func (*Condition) ChildCondition

func (c *Condition) ChildCondition() *Condition

ChildCondition returns the child condition.

func (*Condition) Else

func (c *Condition) Else() bool

Else returns true if this is an else condition.

func (*Condition) Evaluate

func (c *Condition) Evaluate(context ConditionContext) (bool, error)

Evaluate evaluates the condition in the given context.

func (*Condition) Left

func (c *Condition) Left() interface{}

Left returns the left side of the condition.

func (*Condition) Operator

func (c *Condition) Operator() string

Operator returns the operator.

func (*Condition) Or

func (c *Condition) Or(condition *Condition)

Or chains this condition with another using OR.

func (*Condition) Right

func (c *Condition) Right() interface{}

Right returns the right side of the condition.

type ConditionContext

type ConditionContext interface {
	Evaluate(expr interface{}) interface{}
}

ConditionContext provides context for evaluating conditions.

type ConditionOperator

type ConditionOperator func(cond *Condition, left, right interface{}) (bool, error)

ConditionOperator is a function type for condition operators.

type Context

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

Context keeps the variable stack and resolves variables, as well as keywords.

func BuildContext

func BuildContext(config ContextConfig) *Context

BuildContext creates a new Context with the given configuration.

func NewContext

func NewContext() *Context

NewContext creates a new Context with default settings.

func (*Context) AddFilters

func (c *Context) AddFilters(filters []interface{})

AddFilters adds filters to this context.

func (*Context) AddWarning

func (c *Context) AddWarning(warning error)

AddWarning adds a warning.

func (*Context) ApplyGlobalFilter

func (c *Context) ApplyGlobalFilter(obj interface{}) interface{}

ApplyGlobalFilter applies the global filter to an object.

func (*Context) ClearInstanceAssigns

func (c *Context) ClearInstanceAssigns()

ClearInstanceAssigns clears the current scope.

func (*Context) Context

func (c *Context) Context() interface{}

Context interface for TagContext

func (*Context) DecrementRenderDepth

func (c *Context) DecrementRenderDepth()

DecrementRenderDepth decrements the render depth.

func (*Context) Environment

func (c *Context) Environment() *Environment

Environment returns the environment.

func (*Context) Errors

func (c *Context) Errors() []error

Errors returns the errors.

func (*Context) Evaluate

func (c *Context) Evaluate(object interface{}) interface{}

Evaluate evaluates an object (calls evaluate if it has that method).

func (*Context) ExceptionRenderer

func (c *Context) ExceptionRenderer() func(error) interface{}

ExceptionRenderer returns the exception renderer.

func (*Context) FindVariable

func (c *Context) FindVariable(key string, raiseOnNotFound bool) interface{}

FindVariable finds a variable starting at local scope and moving up.

func (*Context) Get

func (c *Context) Get(expression string) interface{}

Get gets a variable by evaluating an expression.

func (*Context) GlobalFilter

func (c *Context) GlobalFilter() func(interface{}) interface{}

GlobalFilter returns the global filter function.

func (*Context) HandleError

func (c *Context) HandleError(err error, lineNumber *int) string

HandleError handles an error and returns the rendered error message.

func (*Context) IncrementRenderDepth

func (c *Context) IncrementRenderDepth()

IncrementRenderDepth increments the render depth and checks for stack overflow.

func (*Context) Interrupt

func (c *Context) Interrupt() bool

Interrupt returns true if there are any unhandled interrupts.

func (*Context) Invoke

func (c *Context) Invoke(method string, obj interface{}, args ...interface{}) interface{}

Invoke invokes a filter method.

func (*Context) Key

func (c *Context) Key(key string) bool

Key returns true if the key exists.

func (*Context) LookupAndEvaluate

func (c *Context) LookupAndEvaluate(obj map[string]interface{}, key string, raiseOnNotFound bool) interface{}

LookupAndEvaluate looks up and evaluates a value from an object.

func (*Context) Merge

func (c *Context) Merge(newScopes map[string]interface{})

Merge merges variables into the current local scope.

func (*Context) NewIsolatedSubcontext

func (c *Context) NewIsolatedSubcontext() *Context

NewIsolatedSubcontext creates a new isolated subcontext.

func (*Context) ParseContext

func (c *Context) ParseContext() ParseContextInterface

ParseContext returns a ParseContextInterface (not implemented yet, returns nil). This is needed for TagContext interface but Context doesn't have a ParseContext.

func (*Context) Partial

func (c *Context) Partial() bool

Partial returns whether this is a partial context.

func (*Context) Pop

func (c *Context) Pop()

Pop pops from the stack.

func (*Context) PopInterrupt

func (c *Context) PopInterrupt() interface{}

PopInterrupt pops an interrupt from the stack.

func (*Context) Profiler

func (c *Context) Profiler() *Profiler

Profiler returns the profiler.

func (*Context) Push

func (c *Context) Push(newScope map[string]interface{})

Push pushes a new local scope on the stack.

func (*Context) PushInterrupt

func (c *Context) PushInterrupt(interrupt interface{})

PushInterrupt pushes an interrupt to the stack.

func (*Context) Registers

func (c *Context) Registers() *Registers

Registers returns the registers.

func (*Context) Reset

func (c *Context) Reset()

Reset clears the Context for reuse from the pool. This method must reset all fields to their zero values.

func (*Context) ResourceLimits

func (c *Context) ResourceLimits() *ResourceLimits

ResourceLimits returns the resource limits.

func (*Context) Scopes

func (c *Context) Scopes() []map[string]interface{}

Scopes returns the scopes.

func (*Context) Set

func (c *Context) Set(key string, value interface{})

Set sets a variable in the current scope (innermost/newest scope).

func (*Context) SetExceptionRenderer

func (c *Context) SetExceptionRenderer(renderer func(error) interface{})

SetExceptionRenderer sets the exception renderer.

func (*Context) SetGlobalFilter

func (c *Context) SetGlobalFilter(filter func(interface{}) interface{})

SetGlobalFilter sets the global filter function.

func (*Context) SetLast

func (c *Context) SetLast(key string, value interface{})

SetLast sets a variable in the last scope (outermost/oldest scope). This is used by assign and capture tags, matching Ruby's context.scopes.last[@key] = value.

func (*Context) SetPartial

func (c *Context) SetPartial(partial bool)

SetPartial sets whether this is a partial context.

func (*Context) SetProfiler

func (c *Context) SetProfiler(profiler *Profiler)

SetProfiler sets the profiler.

func (*Context) SetResourceLimits

func (c *Context) SetResourceLimits(rl *ResourceLimits)

SetResourceLimits sets the resource limits.

func (*Context) SetStrictFilters

func (c *Context) SetStrictFilters(strict bool)

SetStrictFilters sets strict filters mode.

func (*Context) SetStrictVariables

func (c *Context) SetStrictVariables(strict bool)

SetStrictVariables sets strict variables mode.

func (*Context) SetTemplateName

func (c *Context) SetTemplateName(name string)

SetTemplateName sets the template name.

func (*Context) Stack

func (c *Context) Stack(newScope map[string]interface{}, fn func())

Stack pushes a new scope, executes the function, then pops.

func (*Context) Strainer

func (c *Context) Strainer() *StrainerTemplate

Strainer returns the strainer (creates if needed).

func (*Context) StrictFilters

func (c *Context) StrictFilters() bool

StrictFilters returns whether strict filters mode is enabled.

func (*Context) StrictVariables

func (c *Context) StrictVariables() bool

StrictVariables returns whether strict variables mode is enabled.

func (*Context) TagDisabled

func (c *Context) TagDisabled(tagName string) bool

TagDisabled returns true if a tag is disabled.

func (*Context) TemplateName

func (c *Context) TemplateName() string

TemplateName returns the template name.

func (*Context) Warnings

func (c *Context) Warnings() []error

Warnings returns the warnings.

func (*Context) WithDisabledTags

func (c *Context) WithDisabledTags(tagNames []string, fn func())

WithDisabledTags executes a function with disabled tags.

type ContextConfig

type ContextConfig struct {
	Registers          interface{}
	Environment        *Environment
	OuterScope         map[string]interface{}
	ResourceLimits     *ResourceLimits
	Environments       []map[string]interface{}
	StaticEnvironments []map[string]interface{}
	RethrowErrors      bool
}

ContextConfig configures a Context.

type ContextError

type ContextError struct {
	Err *Error
}

ContextError represents a context error.

func NewContextError

func NewContextError(message string) *ContextError

NewContextError creates a new ContextError with the given message.

func (*ContextError) Error

func (e *ContextError) Error() string

type ContinueInterrupt

type ContinueInterrupt struct {
	*Interrupt
}

ContinueInterrupt is thrown whenever a {% continue %} is called.

func NewContinueInterrupt

func NewContinueInterrupt() *ContinueInterrupt

NewContinueInterrupt creates a new continue interrupt.

type Deprecations

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

Deprecations handles deprecation warnings.

func (*Deprecations) Reset

func (d *Deprecations) Reset()

Reset clears all warned deprecations (useful for testing).

func (*Deprecations) Warn

func (d *Deprecations) Warn(name, alternative string)

Warn issues a deprecation warning if it hasn't been warned about before.

type DisabledError

type DisabledError struct {
	Err *Error
}

DisabledError represents a disabled error.

func NewDisabledError

func NewDisabledError(message string) *DisabledError

NewDisabledError creates a new DisabledError with the given message.

func (*DisabledError) Error

func (e *DisabledError) Error() string

type Document

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

Document represents the root node of a Liquid template parse tree.

func NewDocument

func NewDocument(parseContext ParseContextInterface) *Document

NewDocument creates a new Document.

func ParseDocument

func ParseDocument(tokenizer *Tokenizer, parseContext ParseContextInterface) (*Document, error)

ParseDocument parses tokens into a Document. Catches panics from parsing and converts them to errors to prevent application crashes.

func (*Document) Body

func (d *Document) Body() *BlockBody

Body returns the body.

func (*Document) Nodelist

func (d *Document) Nodelist() []interface{}

Nodelist returns the nodelist from the body.

func (*Document) Parse

func (d *Document) Parse(tokenizer *Tokenizer, parseContext ParseContextInterface) error

Parse parses tokens into the document.

func (*Document) ParseContext

func (d *Document) ParseContext() ParseContextInterface

ParseContext returns the parse context.

func (*Document) Render

func (d *Document) Render(context TagContext) string

Render renders the document and returns the result as a string.

func (*Document) RenderToOutputBuffer

func (d *Document) RenderToOutputBuffer(context TagContext, output *string)

RenderToOutputBuffer renders the document to an output buffer.

func (*Document) UnknownTag

func (d *Document) UnknownTag(tag, markup string, tokenizer *Tokenizer) error

UnknownTag handles unknown tags encountered during parsing.

type Drop

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

Drop is a base class for drops that allows exporting DOM-like things to liquid. Methods of drops are callable. The main use for liquid drops is to implement lazy loaded objects.

func NewDrop

func NewDrop() *Drop

NewDrop creates a new Drop instance.

func (*Drop) Context

func (d *Drop) Context() *Context

Context returns the context.

func (*Drop) InvokeDrop

func (d *Drop) InvokeDrop(methodOrKey string) interface{}

InvokeDrop invokes a method on the drop.

func (*Drop) InvokeDropOld

func (d *Drop) InvokeDropOld(methodOrKey string) interface{}

InvokeDropOld invokes a method on the drop (old implementation).

func (*Drop) Key

func (d *Drop) Key(name string) bool

Key returns true if the key exists (drops always return true).

func (*Drop) LiquidMethodMissing

func (d *Drop) LiquidMethodMissing(method string) interface{}

LiquidMethodMissing is called when a method is not found. It can be overridden by specific drop types.

func (*Drop) SetContext

func (d *Drop) SetContext(ctx *Context)

SetContext sets the context for the drop.

func (*Drop) String

func (d *Drop) String() string

String returns the string representation of the drop.

type ElseCondition

type ElseCondition struct {
	*Condition
}

ElseCondition represents an else condition.

func NewElseCondition

func NewElseCondition() *ElseCondition

NewElseCondition creates a new ElseCondition.

func (*ElseCondition) Else

func (e *ElseCondition) Else() bool

Else returns true for else conditions.

func (*ElseCondition) Evaluate

func (e *ElseCondition) Evaluate(context ConditionContext) (bool, error)

Evaluate always returns true for else conditions.

type Environment

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

Environment is the container for all configuration options of Liquid, such as the registered tags, filters, and the default error mode.

func NewEnvironment

func NewEnvironment() *Environment

NewEnvironment creates a new environment instance.

func NewEnvironmentWithStandardTags

func NewEnvironmentWithStandardTags() *Environment

NewEnvironmentWithStandardTags creates a new environment and registers all standard tags. This function avoids import cycles by being called from outside the liquid package.

func (*Environment) CreateStrainer

func (e *Environment) CreateStrainer(context interface{ Context() interface{} }, filters []interface{}, strictFilters bool) *StrainerTemplate

CreateStrainer creates a new strainer instance with the given filters.

func (*Environment) ErrorMode

func (e *Environment) ErrorMode() string

ErrorMode returns the error mode.

func (*Environment) ExceptionRenderer

func (e *Environment) ExceptionRenderer() func(error) interface{}

ExceptionRenderer returns the exception renderer.

func (*Environment) FileSystem

func (e *Environment) FileSystem() FileSystem

FileSystem returns the file system.

func (*Environment) FilterMethodNames

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

FilterMethodNames returns the names of all filter methods.

func (*Environment) RegisterFilter

func (e *Environment) RegisterFilter(filter interface{}) error

RegisterFilter registers a new filter with the environment.

func (*Environment) RegisterFilters

func (e *Environment) RegisterFilters(filters []interface{}) error

RegisterFilters registers multiple filters with this environment.

func (*Environment) RegisterTag

func (e *Environment) RegisterTag(name string, tagClass interface{})

RegisterTag registers a new tag with the environment.

func (*Environment) SetDefaultResourceLimits

func (e *Environment) SetDefaultResourceLimits(limits map[string]interface{})

SetDefaultResourceLimits sets the default resource limits.

func (*Environment) SetErrorMode

func (e *Environment) SetErrorMode(mode string)

SetErrorMode sets the error mode.

func (*Environment) SetExceptionRenderer

func (e *Environment) SetExceptionRenderer(renderer func(error) interface{})

SetExceptionRenderer sets the exception renderer.

func (*Environment) SetFileSystem

func (e *Environment) SetFileSystem(fs FileSystem)

SetFileSystem sets the file system.

func (*Environment) TagForName

func (e *Environment) TagForName(name string) interface{}

TagForName returns the tag class for the given tag name.

func (*Environment) Tags

func (e *Environment) Tags() map[string]interface{}

Tags returns the tags map.

type Error

type Error struct {
	Message       string
	LineNumber    *int
	TemplateName  string
	MarkupContext string
}

Error is the base error type for all Liquid errors.

func (*Error) Error

func (e *Error) Error() string

func (*Error) String

func (e *Error) String(withPrefix bool) string

String returns the error message with optional prefix.

type Expression

type Expression struct{}

Expression represents a parsed Liquid expression.

type FileSystem

type FileSystem interface {
	ReadTemplateFile(templatePath string) (string, error)
}

FileSystem is an interface for retrieving template files.

type FileSystemError

type FileSystemError struct {
	Err *Error
}

FileSystemError represents a file system error.

func NewFileSystemError

func NewFileSystemError(message string) *FileSystemError

NewFileSystemError creates a new FileSystemError with the given message.

func (*FileSystemError) Error

func (e *FileSystemError) Error() string

type FloatDomainError

type FloatDomainError struct {
	Err *Error
}

FloatDomainError represents a float domain error.

func NewFloatDomainError

func NewFloatDomainError(message string) *FloatDomainError

NewFloatDomainError creates a new FloatDomainError with the given message.

func (*FloatDomainError) Error

func (e *FloatDomainError) Error() string

type ForloopDrop

type ForloopDrop struct {
	*Drop
	// contains filtered or unexported fields
}

ForloopDrop provides information about a parent for loop.

func NewForloopDrop

func NewForloopDrop(name string, length int, parentloop *ForloopDrop) *ForloopDrop

NewForloopDrop creates a new ForloopDrop.

func (*ForloopDrop) First

func (f *ForloopDrop) First() bool

First returns true if the current iteration is the first.

func (*ForloopDrop) Increment

func (f *ForloopDrop) Increment()

Increment increments the index (protected method).

func (*ForloopDrop) Index

func (f *ForloopDrop) Index() int

Index returns the 1-based index of the current iteration.

func (*ForloopDrop) Index0

func (f *ForloopDrop) Index0() int

Index0 returns the 0-based index of the current iteration.

func (*ForloopDrop) InvokeDrop

func (f *ForloopDrop) InvokeDrop(methodOrKey string) interface{}

InvokeDrop invokes a method on the forloop drop.

func (*ForloopDrop) Last

func (f *ForloopDrop) Last() bool

Last returns true if the current iteration is the last.

func (*ForloopDrop) Length

func (f *ForloopDrop) Length() int

Length returns the total number of iterations in the loop.

func (*ForloopDrop) Name

func (f *ForloopDrop) Name() string

Name returns the name of the loop.

func (*ForloopDrop) Parentloop

func (f *ForloopDrop) Parentloop() *ForloopDrop

Parentloop returns the parent forloop object. Returns nil if the current for loop isn't nested inside another for loop.

func (*ForloopDrop) Rindex

func (f *ForloopDrop) Rindex() int

Rindex returns the 1-based index of the current iteration, in reverse order.

func (*ForloopDrop) Rindex0

func (f *ForloopDrop) Rindex0() int

Rindex0 returns the 0-based index of the current iteration, in reverse order.

type I18n

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

I18n handles internationalization for Liquid templates.

func NewI18n

func NewI18n(path string) *I18n

NewI18n creates a new I18n instance with the given locale path.

func (*I18n) Locale

func (i *I18n) Locale() (map[string]interface{}, error)

Locale returns the loaded locale data.

func (*I18n) T

func (i *I18n) T(name string, vars map[string]interface{}) string

T is an alias for Translate.

func (*I18n) Translate

func (i *I18n) Translate(name string, vars map[string]interface{}) string

Translate translates a key using the locale, with optional variables for interpolation.

type InputIterator

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

InputIterator wraps input for iteration with context support. Mirrors Ruby's InputIterator class from standardfilters.rb:1032-1094

func NewInputIterator

func NewInputIterator(input interface{}, context *Context) *InputIterator

NewInputIterator creates a new InputIterator.

func (*InputIterator) Compact

func (it *InputIterator) Compact() []interface{}

Compact removes nil items.

func (*InputIterator) Concat

func (it *InputIterator) Concat(args interface{}) []interface{}

Concat concatenates with another array.

func (*InputIterator) Each

func (it *InputIterator) Each(fn func(interface{}))

Each iterates over items, converting them to liquid values.

func (*InputIterator) Empty

func (it *InputIterator) Empty() bool

Empty checks if the iterator is empty.

func (*InputIterator) Join

func (it *InputIterator) Join(glue string) string

Join joins items with a glue string.

func (*InputIterator) Reverse

func (it *InputIterator) Reverse() []interface{}

Reverse returns items in reverse order.

func (*InputIterator) ToArray

func (it *InputIterator) ToArray() []interface{}

ToArray converts the iterator to an array.

func (*InputIterator) Uniq

func (it *InputIterator) Uniq(keyFunc func(interface{}) interface{}) []interface{}

Uniq returns unique items.

type InternalError

type InternalError struct {
	Err *Error
}

InternalError represents an internal error.

func NewInternalError

func NewInternalError(message string) *InternalError

NewInternalError creates a new InternalError with the given message.

func (*InternalError) Error

func (e *InternalError) Error() string

type Interrupt

type Interrupt struct {
	Message string
}

Interrupt is any command that breaks processing of a block (ex: a for loop).

func NewInterrupt

func NewInterrupt(message string) *Interrupt

NewInterrupt creates a new interrupt with the given message.

type Lexer

type Lexer struct{}

Lexer tokenizes expressions.

func (*Lexer) Tokenize

func (l *Lexer) Tokenize(ss *StringScanner) ([]Token, error)

Tokenize tokenizes the input string scanner and returns a slice of tokens.

type LocalFileSystem

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

LocalFileSystem retrieves template files from the local file system. Template files are named with an underscore prefix and .liquid extension, similar to Rails partials.

func NewLocalFileSystem

func NewLocalFileSystem(root, pattern string) *LocalFileSystem

NewLocalFileSystem creates a new LocalFileSystem with the given root directory. The pattern defaults to "_%s.liquid" if not provided.

func (*LocalFileSystem) FullPath

func (l *LocalFileSystem) FullPath(templatePath string) (string, error)

FullPath returns the full path to a template file.

func (*LocalFileSystem) ReadTemplateFile

func (l *LocalFileSystem) ReadTemplateFile(templatePath string) (string, error)

ReadTemplateFile reads a template file from the file system.

type MemoryError

type MemoryError struct {
	Err *Error
}

MemoryError represents a memory error.

func NewMemoryError

func NewMemoryError(message string) *MemoryError

NewMemoryError creates a new MemoryError with the given message.

func (*MemoryError) Error

func (e *MemoryError) Error() string

type MethodLiteral

type MethodLiteral struct {
	MethodName string
	ToString   string
}

MethodLiteral represents a method literal (blank, empty).

type MethodOverrideError

type MethodOverrideError struct {
	Err *Error
}

MethodOverrideError represents a method override error.

func NewMethodOverrideError

func NewMethodOverrideError(message string) *MethodOverrideError

NewMethodOverrideError creates a new MethodOverrideError with the given message.

func (*MethodOverrideError) Error

func (e *MethodOverrideError) Error() string

type ParseContext

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

ParseContext represents the context during template parsing.

func NewParseContext

func NewParseContext(options ParseContextOptions) *ParseContext

NewParseContext creates a new ParseContext.

func (*ParseContext) AddWarning

func (pc *ParseContext) AddWarning(warning error)

AddWarning adds a warning.

func (*ParseContext) DecrementDepth

func (pc *ParseContext) DecrementDepth()

DecrementDepth decrements the depth.

func (*ParseContext) Depth

func (pc *ParseContext) Depth() int

Depth returns the depth.

func (*ParseContext) Environment

func (pc *ParseContext) Environment() *Environment

Environment returns the environment.

func (*ParseContext) ErrorMode

func (pc *ParseContext) ErrorMode() string

ErrorMode returns the error mode.

func (*ParseContext) GetOption

func (pc *ParseContext) GetOption(key string) interface{}

GetOption gets an option value.

func (*ParseContext) IncrementDepth

func (pc *ParseContext) IncrementDepth()

IncrementDepth increments the depth.

func (*ParseContext) LineNumber

func (pc *ParseContext) LineNumber() *int

LineNumber returns the line number.

func (*ParseContext) Locale

func (pc *ParseContext) Locale() *I18n

Locale returns the locale.

func (*ParseContext) NewBlockBody

func (pc *ParseContext) NewBlockBody() *BlockBody

NewBlockBody creates a new BlockBody.

func (*ParseContext) NewParser

func (pc *ParseContext) NewParser(input string) *Parser

NewParser creates a new Parser with the shared StringScanner.

func (*ParseContext) NewTokenizer

func (pc *ParseContext) NewTokenizer(source string, lineNumbers bool, startLineNumber *int, forLiquidTag bool) *Tokenizer

NewTokenizer creates a new Tokenizer with the shared StringScanner.

func (*ParseContext) ParseExpression

func (pc *ParseContext) ParseExpression(markup string) interface{}

ParseExpression parses an expression.

func (*ParseContext) ParseExpressionSafe

func (pc *ParseContext) ParseExpressionSafe(markup string, safe bool) interface{}

ParseExpressionSafe parses an expression with safe flag.

func (*ParseContext) Partial

func (pc *ParseContext) Partial() bool

Partial returns whether this is a partial parse.

func (*ParseContext) SafeParseCompleteExpression

func (pc *ParseContext) SafeParseCompleteExpression(parser *Parser) interface{}

SafeParseCompleteExpression parses a complete expression and validates all tokens are consumed. This is used for standalone expression parsing where we expect the entire input to be a valid expression.

func (*ParseContext) SafeParseExpression

func (pc *ParseContext) SafeParseExpression(parser *Parser) interface{}

SafeParseExpression safely parses an expression. In strict/rigid mode, errors are propagated. In lax mode, errors return nil.

func (*ParseContext) SetLineNumber

func (pc *ParseContext) SetLineNumber(ln *int)

SetLineNumber sets the line number.

func (*ParseContext) SetPartial

func (pc *ParseContext) SetPartial(partial bool)

SetPartial sets whether this is a partial parse.

func (*ParseContext) SetTrimWhitespace

func (pc *ParseContext) SetTrimWhitespace(tw bool)

SetTrimWhitespace sets whether to trim whitespace.

func (*ParseContext) TrimWhitespace

func (pc *ParseContext) TrimWhitespace() bool

TrimWhitespace returns whether to trim whitespace.

func (*ParseContext) Warnings

func (pc *ParseContext) Warnings() []error

Warnings returns the warnings.

type ParseContextInterface

type ParseContextInterface interface {
	ParseExpression(markup string) interface{}
	SafeParseExpression(parser *Parser) interface{}
	NewParser(markup string) *Parser
	LineNumber() *int
	SetLineNumber(*int)
	Environment() *Environment
	TrimWhitespace() bool
	SetTrimWhitespace(bool)
	Depth() int
	IncrementDepth()
	DecrementDepth()
	NewBlockBody() *BlockBody
	NewTokenizer(source string, lineNumbers bool, startLineNumber *int, forLiquidTag bool) *Tokenizer
	ErrorMode() string
	AddWarning(error)
}

ParseContextInterface interface for parsing expressions This interface is implemented by ParseContext struct

type ParseContextOptions

type ParseContextOptions struct {
	Environment     *Environment
	Locale          *I18n
	ExpressionCache map[string]interface{}
	TemplateOptions map[string]interface{}
	ErrorMode       string
}

ParseContextOptions configures a ParseContext.

type ParseTreeVisitor

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

ParseTreeVisitor visits nodes in a parse tree.

func ForParseTreeVisitor

func ForParseTreeVisitor(node interface{}, callbacks map[reflect.Type]ParseTreeVisitorCallback) *ParseTreeVisitor

ForParseTreeVisitor creates a ParseTreeVisitor for a node, using node-specific visitor if available.

func NewParseTreeVisitor

func NewParseTreeVisitor(node interface{}, callbacks map[reflect.Type]ParseTreeVisitorCallback) *ParseTreeVisitor

NewParseTreeVisitor creates a new ParseTreeVisitor.

func (*ParseTreeVisitor) AddCallbackFor

func (ptv *ParseTreeVisitor) AddCallbackFor(types []interface{}, callback ParseTreeVisitorCallback) *ParseTreeVisitor

AddCallbackFor adds a callback for specific node types.

func (*ParseTreeVisitor) Visit

func (ptv *ParseTreeVisitor) Visit(context interface{}) []interface{}

Visit visits the parse tree and returns results.

type ParseTreeVisitorCallback

type ParseTreeVisitorCallback func(node interface{}, context interface{}) (interface{}, interface{})

ParseTreeVisitorCallback is a function type for visitor callbacks.

type Parser

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

Parser parses expressions from tokens.

func NewParser

func NewParser(input interface{}) *Parser

NewParser creates a new parser from a string scanner or string.

func (*Parser) Argument

func (p *Parser) Argument() (string, error)

Argument parses an argument (possibly a keyword argument).

func (*Parser) Consume

func (p *Parser) Consume(tokenType interface{}) (string, error)

Consume consumes a token of the given type (or any type if nil).

func (*Parser) ConsumeOptional

func (p *Parser) ConsumeOptional(tokenType string) (string, bool)

ConsumeOptional consumes a token if it matches the type, returns false otherwise.

func (*Parser) Error

func (p *Parser) Error() error

Error returns the lexer error if one occurred during initialization.

func (*Parser) Expression

func (p *Parser) Expression() (string, error)

Expression parses an expression.

func (*Parser) ID

func (p *Parser) ID(str string) (string, bool)

ID checks if the next token is an identifier with the given name.

func (*Parser) Jump

func (p *Parser) Jump(point int)

Jump sets the parser position to the given point.

func (*Parser) Look

func (p *Parser) Look(tokenType string, ahead int) bool

Look checks if a token of the given type is at the current position (or ahead).

func (*Parser) VariableLookups

func (p *Parser) VariableLookups() (string, error)

VariableLookups parses variable lookups (dots and brackets).

type ParserSwitching

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

ParserSwitching provides methods for switching between different parsing modes. This is typically embedded in types that need parsing functionality.

func (*ParserSwitching) ParseWithSelectedParser

func (p *ParserSwitching) ParseWithSelectedParser(markup string, strictParse, laxParse, rigidParse func(string) error) error

ParseWithSelectedParser parses markup using the parser selected by error mode.

func (*ParserSwitching) RigidMode

func (p *ParserSwitching) RigidMode() bool

RigidMode returns true if error mode is rigid.

func (*ParserSwitching) StrictParseWithErrorModeFallback

func (p *ParserSwitching) StrictParseWithErrorModeFallback(markup string, strictParse, laxParse, rigidParse func(string) error) error

StrictParseWithErrorModeFallback is deprecated. Use ParseWithSelectedParser instead.

type PartialCache

type PartialCache struct{}

PartialCache provides caching for partial templates.

func (*PartialCache) Load

func (pc *PartialCache) Load(templateName string, context interface {
	Registers() *Registers
}, parseContext ParseContextInterface) (interface{}, error)

Load loads a partial template from cache or file system.

type Profiler

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

Profiler enables support for profiling template rendering to help track down performance issues.

To enable profiling, pass Profile: true option to Template.Parse. After Template.Render is called, the template object makes available an instance of this class via the Template.Profiler() method.

This object contains all profiling information, containing information on what tags were rendered, where in the templates these tags live, and how long each tag took to render.

This is a tree structure that keeps track of tags and rendering times inside of {% include %} tags.

Profiler also exposes the total time of the template's render in Profiler.TotalRenderTime().

All render times are in seconds. There is a small performance hit when profiling is enabled.

func NewProfiler

func NewProfiler() *Profiler

NewProfiler creates a new Profiler instance.

func (*Profiler) At

func (p *Profiler) At(idx int) *Timing

At returns the child at the given index.

func (*Profiler) Children

func (p *Profiler) Children() []*Timing

Children returns the profiler children. If there's only one child, return its children instead (to skip the root wrapper).

func (*Profiler) Length

func (p *Profiler) Length() int

Length returns the number of children.

func (*Profiler) Profile

func (p *Profiler) Profile(templateName string, fn func())

Profile profiles a template render. Nested renders are done from a tag that already has a timing node.

func (*Profiler) ProfileNode

func (p *Profiler) ProfileNode(templateName, code string, lineNumber *int, fn func())

ProfileNode profiles a single node (tag or variable).

func (*Profiler) TotalRenderTime

func (p *Profiler) TotalRenderTime() float64

TotalRenderTime returns the total render time (alias for TotalTime).

func (*Profiler) TotalTime

func (p *Profiler) TotalTime() float64

TotalTime returns the total render time in seconds.

type Range

type Range struct {
	Start int
	End   int
}

Range represents a simple integer range.

func (*Range) String

func (r *Range) String() string

String returns the string representation of the range (e.g., "1..5").

type RangeLookup

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

RangeLookup represents a range lookup expression (start..end).

func NewRangeLookup

func NewRangeLookup(startObj, endObj interface{}) *RangeLookup

NewRangeLookup creates a new RangeLookup.

func (*RangeLookup) EndObj

func (rl *RangeLookup) EndObj() interface{}

EndObj returns the end object.

func (*RangeLookup) StartObj

func (rl *RangeLookup) StartObj() interface{}

StartObj returns the start object.

type Registers

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

Registers provides a registry for template-level data. It supports both static (immutable) and dynamic (mutable) values.

func NewRegisters

func NewRegisters(registers interface{}) *Registers

NewRegisters creates a new Registers instance.

func (*Registers) Changes

func (r *Registers) Changes() map[string]interface{}

Changes returns the changes map.

func (*Registers) Delete

func (r *Registers) Delete(key string)

Delete deletes a key from changes.

func (*Registers) Fetch

func (r *Registers) Fetch(key string, defaultValue interface{}) interface{}

Fetch gets a value with a default or block.

func (*Registers) Get

func (r *Registers) Get(key string) interface{}

Get gets a value from the registers (checks changes first, then static).

func (*Registers) HasKey

func (r *Registers) HasKey(key string) bool

HasKey returns true if the key exists in either changes or static.

func (*Registers) Set

func (r *Registers) Set(key string, value interface{})

Set sets a value in the registers (creates a change).

func (*Registers) Static

func (r *Registers) Static() map[string]interface{}

Static returns the static registers map.

type RenderOptions

type RenderOptions struct {
	Output            *string
	Registers         map[string]interface{}
	GlobalFilter      func(interface{}) interface{}
	ExceptionRenderer func(error) interface{}
	Filters           []interface{}
	StrictVariables   bool
	StrictFilters     bool
}

RenderOptions contains options for rendering a template.

type ResourceLimits

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

ResourceLimits tracks and enforces resource limits during template rendering.

func NewResourceLimits

func NewResourceLimits(config ResourceLimitsConfig) *ResourceLimits

NewResourceLimits creates a new ResourceLimits instance.

func (*ResourceLimits) AssignScore

func (rl *ResourceLimits) AssignScore() int

AssignScore returns the current assign score.

func (*ResourceLimits) AssignScoreLimit

func (rl *ResourceLimits) AssignScoreLimit() *int

AssignScoreLimit returns the assign score limit.

func (*ResourceLimits) IncrementAssignScore

func (rl *ResourceLimits) IncrementAssignScore(amount int)

IncrementAssignScore increments the assign score.

func (*ResourceLimits) IncrementRenderScore

func (rl *ResourceLimits) IncrementRenderScore(amount int)

IncrementRenderScore increments the render score.

func (*ResourceLimits) IncrementWriteScore

func (rl *ResourceLimits) IncrementWriteScore(output string)

IncrementWriteScore updates either render_length or assign_score based on whether writes are captured.

func (*ResourceLimits) Reached

func (rl *ResourceLimits) Reached() bool

Reached returns true if limits have been reached.

func (*ResourceLimits) RenderLengthLimit

func (rl *ResourceLimits) RenderLengthLimit() *int

RenderLengthLimit returns the render length limit.

func (*ResourceLimits) RenderScore

func (rl *ResourceLimits) RenderScore() int

RenderScore returns the current render score.

func (*ResourceLimits) Reset

func (rl *ResourceLimits) Reset()

Reset resets all scores and flags.

func (*ResourceLimits) WithCapture

func (rl *ResourceLimits) WithCapture(fn func())

WithCapture executes a function with capture tracking.

type ResourceLimitsConfig

type ResourceLimitsConfig struct {
	RenderLengthLimit *int
	RenderScoreLimit  *int
	AssignScoreLimit  *int
}

ResourceLimitsConfig configures resource limits.

type SnippetDrop

type SnippetDrop struct {
	*Drop
	// contains filtered or unexported fields
}

SnippetDrop represents a snippet drop.

func NewSnippetDrop

func NewSnippetDrop(body string, name string, filename string) *SnippetDrop

NewSnippetDrop creates a new SnippetDrop.

func (*SnippetDrop) Body

func (s *SnippetDrop) Body() string

Body returns the body of the snippet.

func (*SnippetDrop) Filename

func (s *SnippetDrop) Filename() string

Filename returns the filename of the snippet.

func (*SnippetDrop) InvokeDrop

func (s *SnippetDrop) InvokeDrop(methodOrKey string) interface{}

InvokeDrop invokes a method on the snippet drop.

func (*SnippetDrop) Name

func (s *SnippetDrop) Name() string

Name returns the name of the snippet.

func (*SnippetDrop) String

func (s *SnippetDrop) String() string

String returns the string representation.

func (*SnippetDrop) ToPartial

func (s *SnippetDrop) ToPartial() string

ToPartial returns the body as a partial.

type StackLevelError

type StackLevelError struct {
	Err *Error
}

StackLevelError represents a stack level error.

func NewStackLevelError

func NewStackLevelError(message string) *StackLevelError

NewStackLevelError creates a new StackLevelError with the given message.

func (*StackLevelError) Error

func (e *StackLevelError) Error() string

type StandardError

type StandardError struct {
	Err *Error
}

StandardError represents a standard error.

func NewStandardError

func NewStandardError(message string) *StandardError

NewStandardError creates a new StandardError with the given message.

func (*StandardError) Error

func (e *StandardError) Error() string

type StandardFilters

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

StandardFilters provides standard filter implementations. This is a struct with methods that can be used as filters.

func (*StandardFilters) Abs

func (sf *StandardFilters) Abs(input interface{}) interface{}

Abs returns the absolute value of a number. Mirrors Ruby's abs from standardfilters.rb:792

func (*StandardFilters) Append

func (sf *StandardFilters) Append(input interface{}, str interface{}) string

Append adds a string to the end. Mirrors Ruby's append from standardfilters.rb:665

func (*StandardFilters) AtLeast

func (sf *StandardFilters) AtLeast(input interface{}, n interface{}) interface{}

AtLeast limits a number to a minimum value. Mirrors Ruby's at_least from standardfilters.rb:905

func (*StandardFilters) AtMost

func (sf *StandardFilters) AtMost(input interface{}, n interface{}) interface{}

AtMost limits a number to a maximum value. Mirrors Ruby's at_most from standardfilters.rb:920

func (*StandardFilters) Base64Decode

func (sf *StandardFilters) Base64Decode(input interface{}) (string, error)

Base64Decode decodes a string in Base64 format.

func (*StandardFilters) Base64Encode

func (sf *StandardFilters) Base64Encode(input interface{}) string

Base64Encode encodes a string to Base64 format.

func (*StandardFilters) Base64URLSafeDecode

func (sf *StandardFilters) Base64URLSafeDecode(input interface{}) (string, error)

Base64URLSafeDecode decodes a string in URL-safe Base64 format.

func (*StandardFilters) Base64URLSafeEncode

func (sf *StandardFilters) Base64URLSafeEncode(input interface{}) string

Base64URLSafeEncode encodes a string to URL-safe Base64 format.

func (*StandardFilters) Capitalize

func (sf *StandardFilters) Capitalize(input interface{}) string

Capitalize capitalizes the first word in a string and downcases the remaining characters.

func (*StandardFilters) Ceil

func (sf *StandardFilters) Ceil(input interface{}) (int, error)

Ceil rounds a number up to the nearest integer. Mirrors Ruby's ceil from standardfilters.rb:879

func (*StandardFilters) Compact

func (sf *StandardFilters) Compact(input interface{}, property interface{}) interface{}

Compact removes nil items from an array. Mirrors Ruby's compact from standardfilters.rb:557

func (*StandardFilters) Concat

func (sf *StandardFilters) Concat(input interface{}, array interface{}) (interface{}, error)

Concat concatenates two arrays. Mirrors Ruby's concat from standardfilters.rb:682

func (*StandardFilters) Date

func (sf *StandardFilters) Date(input interface{}, format interface{}) interface{}

Date formats a date using strftime-style format codes.

func (*StandardFilters) Default

func (sf *StandardFilters) Default(input interface{}, defaultValue interface{}, options interface{}) interface{}

Default returns a default value if input is nil, false, or empty. Mirrors Ruby's default from standardfilters.rb:940

func (*StandardFilters) DividedBy

func (sf *StandardFilters) DividedBy(input interface{}, operand interface{}) (interface{}, error)

DividedBy divides two numbers. Mirrors Ruby's divided_by from standardfilters.rb:837

func (*StandardFilters) Downcase

func (sf *StandardFilters) Downcase(input interface{}) string

Downcase converts a string to all lowercase characters.

func (*StandardFilters) Escape

func (sf *StandardFilters) Escape(input interface{}) string

Escape escapes special characters in HTML.

func (*StandardFilters) EscapeOnce

func (sf *StandardFilters) EscapeOnce(input interface{}) string

EscapeOnce escapes a string without changing characters that have already been escaped.

func (*StandardFilters) Find

func (sf *StandardFilters) Find(input interface{}, property interface{}, targetValue interface{}) interface{}

Find returns the first array item with a property value. Mirrors Ruby's find from standardfilters.rb:473

func (*StandardFilters) FindIndex

func (sf *StandardFilters) FindIndex(input interface{}, property interface{}, targetValue interface{}) interface{}

FindIndex returns the index of the first array item with a property value. Mirrors Ruby's find_index from standardfilters.rb:486

func (*StandardFilters) First

func (sf *StandardFilters) First(input interface{}) interface{}

First returns the first element of an array.

func (*StandardFilters) Floor

func (sf *StandardFilters) Floor(input interface{}) (int, error)

Floor rounds a number down to the nearest integer. Mirrors Ruby's floor from standardfilters.rb:892

func (*StandardFilters) H

func (sf *StandardFilters) H(input interface{}) string

H is an alias for Escape.

func (*StandardFilters) Has

func (sf *StandardFilters) Has(input interface{}, property interface{}, targetValue interface{}) bool

Has tests if any array item has a property value. Mirrors Ruby's has from standardfilters.rb:460

func (*StandardFilters) Join

func (sf *StandardFilters) Join(input interface{}, separator interface{}) string

Join joins array elements with a separator.

func (*StandardFilters) Last

func (sf *StandardFilters) Last(input interface{}) interface{}

Last returns the last element of an array.

func (*StandardFilters) Lstrip

func (sf *StandardFilters) Lstrip(input interface{}) string

Lstrip strips whitespace from the left end of a string.

func (*StandardFilters) Map

func (sf *StandardFilters) Map(input interface{}, property interface{}) (interface{}, error)

Map extracts property values from array items. Mirrors Ruby's map from standardfilters.rb:535

func (*StandardFilters) Minus

func (sf *StandardFilters) Minus(input interface{}, operand interface{}) interface{}

Minus subtracts two numbers. Mirrors Ruby's minus from standardfilters.rb:815

func (*StandardFilters) Modulo

func (sf *StandardFilters) Modulo(input interface{}, operand interface{}) (interface{}, error)

Modulo returns the remainder of division. Mirrors Ruby's modulo from standardfilters.rb:850

func (*StandardFilters) NewlineToBr

func (sf *StandardFilters) NewlineToBr(input interface{}) string

NewlineToBr converts newlines to HTML line breaks. Mirrors Ruby's newline_to_br from standardfilters.rb:709

func (*StandardFilters) Plus

func (sf *StandardFilters) Plus(input interface{}, operand interface{}) interface{}

Plus adds two numbers. Mirrors Ruby's plus from standardfilters.rb:804

func (*StandardFilters) Prepend

func (sf *StandardFilters) Prepend(input interface{}, str interface{}) string

Prepend adds a string to the beginning. Mirrors Ruby's prepend from standardfilters.rb:696

func (*StandardFilters) Reject

func (sf *StandardFilters) Reject(input interface{}, property interface{}, targetValue interface{}) interface{}

Reject filters out array items by property value. Mirrors Ruby's reject from standardfilters.rb:447

func (*StandardFilters) Remove

func (sf *StandardFilters) Remove(input interface{}, str interface{}) string

Remove removes all occurrences of a substring. Mirrors Ruby's remove from standardfilters.rb:632

func (*StandardFilters) RemoveFirst

func (sf *StandardFilters) RemoveFirst(input interface{}, str interface{}) string

RemoveFirst removes the first occurrence of a substring. Mirrors Ruby's remove_first from standardfilters.rb:643

func (*StandardFilters) RemoveLast

func (sf *StandardFilters) RemoveLast(input interface{}, str interface{}) string

RemoveLast removes the last occurrence of a substring. Mirrors Ruby's remove_last from standardfilters.rb:654

func (*StandardFilters) Replace

func (sf *StandardFilters) Replace(input interface{}, str interface{}, replacement interface{}) string

Replace replaces all occurrences of a substring. Mirrors Ruby's replace from standardfilters.rb:583

func (*StandardFilters) ReplaceFirst

func (sf *StandardFilters) ReplaceFirst(input interface{}, str interface{}, replacement interface{}) string

ReplaceFirst replaces the first occurrence of a substring. Mirrors Ruby's replace_first from standardfilters.rb:597

func (*StandardFilters) ReplaceLast

func (sf *StandardFilters) ReplaceLast(input interface{}, str interface{}, replacement interface{}) string

ReplaceLast replaces the last occurrence of a substring. Mirrors Ruby's replace_last from standardfilters.rb:611

func (*StandardFilters) Reverse

func (sf *StandardFilters) Reverse(input interface{}) []interface{}

Reverse reverses the order of items in an array. Mirrors Ruby's reverse from standardfilters.rb:523

func (*StandardFilters) Round

func (sf *StandardFilters) Round(input interface{}, n interface{}) (interface{}, error)

Round rounds a number to the nearest integer or specified precision. Mirrors Ruby's round from standardfilters.rb:863

func (*StandardFilters) Rstrip

func (sf *StandardFilters) Rstrip(input interface{}) string

Rstrip strips whitespace from the right end of a string.

func (*StandardFilters) Size

func (sf *StandardFilters) Size(input interface{}) interface{}

Size returns the size of a string or array.

func (*StandardFilters) Slice

func (sf *StandardFilters) Slice(input interface{}, offset interface{}, length interface{}) interface{}

Slice returns a substring or series of array items.

func (*StandardFilters) Sort

func (sf *StandardFilters) Sort(input interface{}, property interface{}) interface{}

Sort sorts items in an array. Mirrors Ruby's sort from standardfilters.rb:378

func (*StandardFilters) SortNatural

func (sf *StandardFilters) SortNatural(input interface{}, property interface{}) interface{}

SortNatural sorts items case-insensitively. Mirrors Ruby's sort_natural from standardfilters.rb:407

func (*StandardFilters) Split

func (sf *StandardFilters) Split(input interface{}, pattern interface{}) []interface{}

Split splits a string into an array of substrings based on a separator.

func (*StandardFilters) Strip

func (sf *StandardFilters) Strip(input interface{}) string

Strip strips whitespace from both ends of a string.

func (*StandardFilters) StripHTML

func (sf *StandardFilters) StripHTML(input interface{}) string

StripHTML strips HTML tags from a string.

func (*StandardFilters) StripNewlines

func (sf *StandardFilters) StripNewlines(input interface{}) string

StripNewlines strips all newline characters from a string. Mirrors Ruby's strip_newlines from standardfilters.rb:354

func (*StandardFilters) Sum

func (sf *StandardFilters) Sum(input interface{}, property interface{}) interface{}

Sum returns the sum of array elements. Mirrors Ruby's sum from standardfilters.rb:953

func (*StandardFilters) Times

func (sf *StandardFilters) Times(input interface{}, operand interface{}) interface{}

Times multiplies two numbers. Mirrors Ruby's times from standardfilters.rb:826

func (*StandardFilters) Truncate

func (sf *StandardFilters) Truncate(input interface{}, length interface{}, truncateString interface{}) string

Truncate truncates a string down to a given number of characters.

func (*StandardFilters) TruncateWords

func (sf *StandardFilters) TruncateWords(input interface{}, words interface{}, truncateString interface{}) string

TruncateWords truncates a string down to a given number of words.

func (*StandardFilters) URLDecode

func (sf *StandardFilters) URLDecode(input interface{}) (string, error)

URLDecode decodes percent-encoded characters.

func (*StandardFilters) URLEncode

func (sf *StandardFilters) URLEncode(input interface{}) string

URLEncode converts URL-unsafe characters to percent-encoded equivalent.

func (*StandardFilters) Uniq

func (sf *StandardFilters) Uniq(input interface{}, property interface{}) interface{}

Uniq removes duplicate items from an array. Mirrors Ruby's uniq from standardfilters.rb:497

func (*StandardFilters) Upcase

func (sf *StandardFilters) Upcase(input interface{}) string

Upcase converts a string to all uppercase characters.

func (*StandardFilters) Where

func (sf *StandardFilters) Where(input interface{}, property interface{}, targetValue interface{}) interface{}

Where filters array items by property value. Mirrors Ruby's where from standardfilters.rb:434

type StrainerTemplate

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

StrainerTemplate is the computed class for the filters system. New filters are mixed into the strainer class which is then instantiated for each liquid template render run.

func NewStrainerTemplate

func NewStrainerTemplate(class *StrainerTemplateClass, context interface{ Context() interface{} }, strictFilters bool) *StrainerTemplate

NewStrainerTemplate creates a new strainer template instance.

func NewStrainerTemplateWithFilters

func NewStrainerTemplateWithFilters(class *StrainerTemplateClass, context interface{ Context() interface{} }, strictFilters bool, filters []interface{}) *StrainerTemplate

NewStrainerTemplateWithFilters creates a new strainer template instance with additional filters.

func (*StrainerTemplate) Invoke

func (st *StrainerTemplate) Invoke(method string, args ...interface{}) (interface{}, error)

Invoke invokes a filter method.

type StrainerTemplateClass

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

StrainerTemplateClass represents a strainer template class that can have filters added.

func NewStrainerTemplateClass

func NewStrainerTemplateClass() *StrainerTemplateClass

NewStrainerTemplateClass creates a new strainer template class.

func (*StrainerTemplateClass) AddFilter

func (stc *StrainerTemplateClass) AddFilter(filter interface{}) error

AddFilter adds a filter module to the strainer template class.

func (*StrainerTemplateClass) FilterMethodNames

func (stc *StrainerTemplateClass) FilterMethodNames() []string

FilterMethodNames returns all filter method names.

func (*StrainerTemplateClass) Invokable

func (stc *StrainerTemplateClass) Invokable(method string) bool

Invokable checks if a method name is invokable.

type StringScanner

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

StringScanner provides a scanner interface similar to Ruby's StringScanner.

func NewStringScanner

func NewStringScanner(source string) *StringScanner

NewStringScanner creates a new StringScanner.

func (*StringScanner) Byteslice

func (s *StringScanner) Byteslice(start, length int) string

Byteslice returns a slice of bytes from start to end.

func (*StringScanner) EOS

func (s *StringScanner) EOS() bool

EOS returns true if we're at the end of the string.

func (*StringScanner) Getch

func (s *StringScanner) Getch() string

Getch gets the next character (handles UTF-8).

func (*StringScanner) PeekByte

func (s *StringScanner) PeekByte() byte

PeekByte returns the byte at the current position without advancing.

func (*StringScanner) Pos

func (s *StringScanner) Pos() int

Pos returns the current position.

func (*StringScanner) Rest

func (s *StringScanner) Rest() string

Rest returns the rest of the string from current position.

func (*StringScanner) Scan

func (s *StringScanner) Scan(pattern *regexp.Regexp) string

Scan scans for the given pattern and advances position if matched.

func (*StringScanner) ScanByte

func (s *StringScanner) ScanByte() byte

ScanByte advances and returns the byte at the current position.

func (*StringScanner) SetPos

func (s *StringScanner) SetPos(pos int)

SetPos sets the current position.

func (*StringScanner) SetString

func (s *StringScanner) SetString(str string)

SetString sets the source string and resets position.

func (*StringScanner) Skip

func (s *StringScanner) Skip(pattern *regexp.Regexp) int

Skip skips the given pattern.

func (*StringScanner) SkipUntil

func (s *StringScanner) SkipUntil(pattern *regexp.Regexp) int

SkipUntil skips until the pattern is found.

func (*StringScanner) String

func (s *StringScanner) String() string

String returns the source string.

func (*StringScanner) Terminate

func (s *StringScanner) Terminate()

Terminate sets position to end of string.

type SyntaxError

type SyntaxError struct {
	Err *Error
}

SyntaxError represents a syntax error.

func NewSyntaxError

func NewSyntaxError(message string) *SyntaxError

NewSyntaxError creates a new SyntaxError with the given message.

func (*SyntaxError) Error

func (e *SyntaxError) Error() string

Error implements the error interface for SyntaxError with custom prefix.

type TablerowloopDrop

type TablerowloopDrop struct {
	*Drop
	// contains filtered or unexported fields
}

TablerowloopDrop provides information about a parent tablerow loop.

func NewTablerowloopDrop

func NewTablerowloopDrop(length int, cols int) *TablerowloopDrop

NewTablerowloopDrop creates a new TablerowloopDrop.

func (*TablerowloopDrop) Col

func (t *TablerowloopDrop) Col() int

Col returns the 1-based index of the current column.

func (*TablerowloopDrop) Col0

func (t *TablerowloopDrop) Col0() int

Col0 returns the 0-based index of the current column.

func (*TablerowloopDrop) ColFirst

func (t *TablerowloopDrop) ColFirst() bool

ColFirst returns true if the current column is the first in the row.

func (*TablerowloopDrop) ColLast

func (t *TablerowloopDrop) ColLast() bool

ColLast returns true if the current column is the last in the row.

func (*TablerowloopDrop) Cols

func (t *TablerowloopDrop) Cols() int

Cols returns the number of columns.

func (*TablerowloopDrop) First

func (t *TablerowloopDrop) First() bool

First returns true if the current iteration is the first.

func (*TablerowloopDrop) Increment

func (t *TablerowloopDrop) Increment()

Increment increments the index and updates row/col.

func (*TablerowloopDrop) Index

func (t *TablerowloopDrop) Index() int

Index returns the 1-based index of the current iteration.

func (*TablerowloopDrop) Index0

func (t *TablerowloopDrop) Index0() int

Index0 returns the 0-based index of the current iteration.

func (*TablerowloopDrop) InvokeDrop

func (t *TablerowloopDrop) InvokeDrop(methodOrKey string) interface{}

InvokeDrop invokes a method on the tablerowloop drop.

func (*TablerowloopDrop) Last

func (t *TablerowloopDrop) Last() bool

Last returns true if the current iteration is the last.

func (*TablerowloopDrop) Length

func (t *TablerowloopDrop) Length() int

Length returns the total number of iterations in the loop.

func (*TablerowloopDrop) Rindex

func (t *TablerowloopDrop) Rindex() int

Rindex returns the 1-based index of the current iteration, in reverse order.

func (*TablerowloopDrop) Rindex0

func (t *TablerowloopDrop) Rindex0() int

Rindex0 returns the 0-based index of the current iteration, in reverse order.

func (*TablerowloopDrop) Row

func (t *TablerowloopDrop) Row() int

Row returns the 1-based index of current row.

type Tag

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

Tag represents a Liquid tag.

func NewTag

func NewTag(tagName, markup string, parseContext ParseContextInterface) *Tag

NewTag creates a new tag instance.

func ParseTag

func ParseTag(tagName, markup string, tokenizer *Tokenizer, parseContext ParseContextInterface) (*Tag, error)

ParseTag parses a tag from tokenizer.

func (*Tag) Blank

func (t *Tag) Blank() bool

Blank returns true if the tag is blank (produces no output).

func (*Tag) LineNumber

func (t *Tag) LineNumber() *int

LineNumber returns the line number.

func (*Tag) Markup

func (t *Tag) Markup() string

Markup returns the tag markup.

func (*Tag) Name

func (t *Tag) Name() string

Name returns the tag name (for backwards compatibility).

func (*Tag) Nodelist

func (t *Tag) Nodelist() []interface{}

Nodelist returns the nodelist (for block tags).

func (*Tag) Parse

func (t *Tag) Parse(tokenizer *Tokenizer) error

Parse parses the tag (can be overridden by subclasses).

func (*Tag) ParseContext

func (t *Tag) ParseContext() ParseContextInterface

ParseContext returns the parse context.

func (*Tag) ParseExpression

func (t *Tag) ParseExpression(markup string, safe bool) interface{}

ParseExpression parses an expression.

func (*Tag) Raw

func (t *Tag) Raw() string

Raw returns the raw tag representation.

func (*Tag) Render

func (t *Tag) Render(context TagContext) string

Render renders the tag (returns empty string by default).

func (*Tag) RenderToOutputBuffer

func (t *Tag) RenderToOutputBuffer(context TagContext, output *string)

RenderToOutputBuffer renders the tag to the output buffer. Note: Due to Go's method dispatch with embedded pointers, this method cannot automatically call overridden Render() methods in subtypes. Tags that override Render() must be handled specially in the rendering code.

func (*Tag) SafeParseExpression

func (t *Tag) SafeParseExpression(parser *Parser) interface{}

SafeParseExpression safely parses an expression.

func (*Tag) SetNodelist

func (t *Tag) SetNodelist(nodelist []interface{})

SetNodelist sets the nodelist.

func (*Tag) TagName

func (t *Tag) TagName() string

TagName returns the tag name.

type TagContext

type TagContext interface {
	TagDisabled(tagName string) bool
	WithDisabledTags(tags []string, fn func())
	HandleError(err error, lineNumber *int) string
	ParseContext() ParseContextInterface
	Evaluate(expr interface{}) interface{}
	FindVariable(key string, raiseOnNotFound bool) interface{}
	Invoke(method string, obj interface{}, args ...interface{}) interface{}
	ApplyGlobalFilter(obj interface{}) interface{}
	Interrupt() bool
	PushInterrupt(interrupt interface{})
	ResourceLimits() *ResourceLimits
	Registers() *Registers
	Context() interface{}
}

TagContext interface for tag rendering context

type Template

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

Template represents a compiled Liquid template. Templates are central to liquid. Interpreting templates is a two step process. First you compile the source code you got. During compile time some extensive error checking is performed. Your code should expect to get some SyntaxErrors.

After you have a compiled template you can then render it. You can use a compiled template over and over again and keep it cached.

Example:

template := liquid.ParseTemplate(source)
result := template.Render(map[string]interface{}{"user_name": "bob"})

func NewTemplate

func NewTemplate(options *TemplateOptions) *Template

NewTemplate creates a new Template instance.

func ParseTemplate

func ParseTemplate(source string, options *TemplateOptions) (*Template, error)

ParseTemplate creates a new Template and parses the source code. To enable profiling, pass in Profile: true as an option.

func (*Template) Assigns

func (t *Template) Assigns() map[string]interface{}

Assigns returns the assigns map.

func (*Template) Errors

func (t *Template) Errors() []error

Errors returns the errors.

func (*Template) InstanceAssigns

func (t *Template) InstanceAssigns() map[string]interface{}

InstanceAssigns returns the instance assigns map.

func (*Template) Name

func (t *Template) Name() string

Name returns the template name.

func (*Template) Parse

func (t *Template) Parse(source string, options *TemplateOptions) (err error)

Parse parses source code. Returns self for easy chaining.

func (*Template) Profiler

func (t *Template) Profiler() *Profiler

Profiler returns the profiler (if profiling was enabled).

func (*Template) Registers

func (t *Template) Registers() map[string]interface{}

Registers returns the registers map.

func (*Template) Render

func (t *Template) Render(assigns interface{}, options *RenderOptions) (output string)

Render renders the template with the given assigns. Render takes a hash with local variables.

Following options can be passed via RenderOptions:

  • Filters: array with local filters
  • Registers: hash with register variables. Those can be accessed from filters and tags and might be useful to integrate liquid more with its host application

func (*Template) RenderBang

func (t *Template) RenderBang(assigns interface{}, options *RenderOptions) string

RenderBang renders the template with rethrow_errors enabled.

func (*Template) RenderToOutputBuffer

func (t *Template) RenderToOutputBuffer(context TagContext, output *string)

RenderToOutputBuffer renders the template to the output buffer.

func (*Template) ResourceLimits

func (t *Template) ResourceLimits() *ResourceLimits

ResourceLimits returns the resource limits.

func (*Template) Root

func (t *Template) Root() *Document

Root returns the root document.

func (*Template) SetName

func (t *Template) SetName(name string)

SetName sets the template name.

func (*Template) SetResourceLimits

func (t *Template) SetResourceLimits(rl *ResourceLimits)

SetResourceLimits sets the resource limits.

func (*Template) SetRoot

func (t *Template) SetRoot(root *Document)

SetRoot sets the root document.

func (*Template) Warnings

func (t *Template) Warnings() []error

Warnings returns the warnings.

type TemplateEncodingError

type TemplateEncodingError struct {
	Err *Error
}

TemplateEncodingError represents a template encoding error.

func NewTemplateEncodingError

func NewTemplateEncodingError(message string) *TemplateEncodingError

NewTemplateEncodingError creates a new TemplateEncodingError with the given message.

func (*TemplateEncodingError) Error

func (e *TemplateEncodingError) Error() string

type TemplateFactory

type TemplateFactory struct{}

TemplateFactory creates template instances.

func NewTemplateFactory

func NewTemplateFactory() *TemplateFactory

NewTemplateFactory creates a new TemplateFactory.

func (*TemplateFactory) For

func (tf *TemplateFactory) For(templateName string) interface{}

For returns a template instance for the given template name.

type TemplateOptions

type TemplateOptions struct {
	Environment       *Environment
	GlobalFilter      func(interface{}) interface{}
	ExceptionRenderer func(error) interface{}
	Registers         map[string]interface{}
	Filters           []interface{}
	Profile           bool
	LineNumbers       bool
	StrictVariables   bool
	StrictFilters     bool
}

TemplateOptions contains options for parsing a template.

type Timing

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

Timing represents a single timing node in the profiler tree.

func (*Timing) Children

func (t *Timing) Children() []*Timing

Children returns the children of this timing node.

func (*Timing) Code

func (t *Timing) Code() string

Code returns the code for this timing node.

func (*Timing) LineNumber

func (t *Timing) LineNumber() *int

LineNumber returns the line number for this timing node.

func (*Timing) Partial

func (t *Timing) Partial() string

Partial returns the template name (alias for TemplateName).

func (*Timing) RenderTime

func (t *Timing) RenderTime() float64

RenderTime returns the render time (alias for TotalTime).

func (*Timing) SelfTime

func (t *Timing) SelfTime() float64

SelfTime returns the self time (total time minus children time).

func (*Timing) TemplateName

func (t *Timing) TemplateName() string

TemplateName returns the template name for this timing node.

func (*Timing) TotalTime

func (t *Timing) TotalTime() float64

TotalTime returns the total time for this timing node in seconds.

type Token

type Token [2]interface{} // [type, value]

Token represents a lexer token with type and value.

func Tokenize

func Tokenize(ss *StringScanner) ([]Token, error)

Tokenize is a convenience function that tokenizes a string scanner.

type Tokenizer

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

Tokenizer tokenizes template source into text, tags, and variables.

func NewTokenizer

func NewTokenizer(source string, stringScanner *StringScanner, lineNumbers bool, startLineNumber *int, forLiquidTag bool) *Tokenizer

NewTokenizer creates a new tokenizer.

func (*Tokenizer) ForLiquidTag

func (t *Tokenizer) ForLiquidTag() bool

ForLiquidTag returns whether this tokenizer is for a liquid tag.

func (*Tokenizer) LineNumber

func (t *Tokenizer) LineNumber() *int

LineNumber returns the current line number.

func (*Tokenizer) Shift

func (t *Tokenizer) Shift() string

Shift returns the next token and advances the offset.

type UndefinedDropMethod

type UndefinedDropMethod struct {
	Err *Error
}

UndefinedDropMethod represents an undefined drop method error.

func NewUndefinedDropMethod

func NewUndefinedDropMethod(message string) *UndefinedDropMethod

NewUndefinedDropMethod creates a new UndefinedDropMethod with the given message.

func (*UndefinedDropMethod) Error

func (e *UndefinedDropMethod) Error() string

type UndefinedFilter

type UndefinedFilter struct {
	Err *Error
}

UndefinedFilter represents an undefined filter error.

func NewUndefinedFilter

func NewUndefinedFilter(message string) *UndefinedFilter

NewUndefinedFilter creates a new UndefinedFilter with the given message.

func (*UndefinedFilter) Error

func (e *UndefinedFilter) Error() string

type UndefinedVariable

type UndefinedVariable struct {
	Err *Error
}

UndefinedVariable represents an undefined variable error.

func NewUndefinedVariable

func NewUndefinedVariable(message string) *UndefinedVariable

NewUndefinedVariable creates a new UndefinedVariable with the given message.

func (*UndefinedVariable) Error

func (e *UndefinedVariable) Error() string

type Usage

type Usage struct{}

Usage provides usage tracking functionality. Currently a placeholder for future implementation.

func (*Usage) Increment

func (u *Usage) Increment(name string)

Increment increments usage count for a given name. Currently a no-op, to be implemented when usage tracking is needed.

type Variable

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

Variable represents a Liquid variable with optional filters.

func NewVariable

func NewVariable(markup string, parseContext ParseContextInterface) *Variable

NewVariable creates a new Variable from markup.

func (*Variable) Evaluate

func (v *Variable) Evaluate(context *Context) interface{}

Render renders the variable. Evaluate evaluates the variable with filters, used when Variable appears in conditions. This ensures that Variables with filters are properly evaluated in if/unless/case conditions.

func (*Variable) Filters

func (v *Variable) Filters() [][]interface{}

Filters returns the filters.

func (*Variable) LineNumber

func (v *Variable) LineNumber() *int

LineNumber returns the line number.

func (*Variable) Name

func (v *Variable) Name() interface{}

Name returns the variable name expression.

func (*Variable) Raw

func (v *Variable) Raw() string

Raw returns the raw markup.

func (*Variable) Render

func (v *Variable) Render(context TagContext) interface{}

func (*Variable) RenderToOutputBuffer

func (v *Variable) RenderToOutputBuffer(context TagContext, output *string)

RenderToOutputBuffer renders the variable to the output buffer.

type VariableLookup

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

VariableLookup represents a variable lookup expression.

func VariableLookupParse

func VariableLookupParse(markup string, ss *StringScanner, cache map[string]interface{}) *VariableLookup

VariableLookupParse parses a markup string into a VariableLookup. Optimization: Uses global cache for better performance across templates.

func (*VariableLookup) Evaluate

func (vl *VariableLookup) Evaluate(context *Context) interface{}

Evaluate evaluates the variable lookup in the given context.

func (*VariableLookup) LookupCommand

func (vl *VariableLookup) LookupCommand(lookupIndex int) bool

LookupCommand returns true if the lookup at the given index is a command method.

func (*VariableLookup) Lookups

func (vl *VariableLookup) Lookups() []interface{}

Lookups returns the lookups.

func (*VariableLookup) Name

func (vl *VariableLookup) Name() interface{}

Name returns the variable name.

type ZeroDivisionError

type ZeroDivisionError struct {
	Err *Error
}

ZeroDivisionError represents a zero division error.

func NewZeroDivisionError

func NewZeroDivisionError(message string) *ZeroDivisionError

NewZeroDivisionError creates a new ZeroDivisionError with the given message.

func (*ZeroDivisionError) Error

func (e *ZeroDivisionError) Error() string

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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