vuego

package module
v0.4.2 Latest Latest
Warning

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

Go to latest
Published: Dec 22, 2025 License: MIT Imports: 24 Imported by: 0

README

vuego

Go Reference Coverage

Vuego is a Vue.js-inspired template engine for Go. Render HTML templates with familiar Vue syntax - no JavaScript runtime required.

Status

Project it in active development. Some changes in API surface are still expected based on feedback and observations.

Quick start

You can use vuego by importing it in your project:

import "github.com/titpetric/vuego"

In your service you create a new vuego renderer.

renderer := vuego.New(
	vuego.WithFS(os.DirFS("templates")),
	vuego.WithFuncs(funcMap),
)

With this you have a vuego.Template. From here you can:

  1. Construct new template rendering contexts with renderer.New and renderer.Load
  2. Manage state with Fill, Set and Get functions
  3. Finalize the rendering context with Render and Layout functions
  4. Additional renderers are provided to render from non-FS sources

An example of a rendering invocation would be:

err = renderer.File(filename).Fill(data).Layout(r.Context(), w)

Layout will use front-matter layout hints to load layouts from layouts/%s.vuego. If no hint is provided, layouts/base.vuego is passed the contents from the previously rendered template. Use Render if you don't want layouts.

For rendering fragments (from variables or otherwise):

  • RenderFile(ctx context.Context, w io.Writer, filename string) error
  • RenderString(ctx context.Context, w io.Writer, templateStr string) error
  • RenderByte(ctx context.Context, w io.Writer, templateData []byte) error
  • RenderReader(ctx context.Context, w io.Writer, r io.Reader) error

An example of a rendering invocation is:

err = renderer.New().Fill(data).RenderString(r.Context(), w, `<li v-for="item in items">{{ item.title }}</li>`)

There's more detail around authoring vuego templates, check documentation:

Features

Vuego supports the following template features:

  • Variable interpolation - {{ variable }} with nested property access
  • Template functions - Pipe-based filter chaining {{ value | upper | trim }}
  • Custom functions - Define custom template functions (FuncMap)
  • Built-in filters - String manipulation, formatting, type conversion
  • Attribute binding - :attr="value" or v-bind:attr="value"
  • Conditional rendering - v-if for showing/hiding elements with function support
  • List rendering - v-for to iterate over arrays with optional index
  • Raw HTML - v-html for unescaped HTML content
  • Component composition - <vuego include> for reusable components
  • Required props - :required attribute for component validation
  • Template wrapping - <template> tag for component boundaries
  • Full documents - Support for complete HTML documents or fragments
  • Automatic escaping - Built-in XSS protection for interpolated values

Playground

Try VueGo in your browser! The interactive playground lets you experiment with templates and see results instantly.

You can run the playground locally, and if you pass a folder as the first parameter, you have a workspace.

# go run github.com/titpetric/vuego/cmd/vuego-playground
2025/11/14 20:07:31 VueGo Playground starting on http://localhost:3000

Documentation

The Template Syntax reference covers four main areas:

  • Values - Variable interpolation, expressions, and filters
  • Directives - Complete reference of all v- directives
  • Components - <vuego> and <template> tags
  • Advanced - Template functions, custom filters, and full documents

Additional resources:

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Component

type Component interface {
	// Render renders the component template to the given writer.
	Render(ctx context.Context, w io.Writer, filename string, data any) error
}

Component is a renderable .vuego template component.

type ExprEvaluator

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

ExprEvaluator wraps expr for evaluating boolean and interpolated expressions. It caches compiled programs to avoid recompilation.

func NewExprEvaluator

func NewExprEvaluator() *ExprEvaluator

NewExprEvaluator creates a new ExprEvaluator with an empty cache.

func (*ExprEvaluator) ClearCache

func (e *ExprEvaluator) ClearCache()

ClearCache clears the program cache (useful for testing or memory management).

func (*ExprEvaluator) Eval

func (e *ExprEvaluator) Eval(expression string, env map[string]any) (any, error)

Eval evaluates an expression against the given environment (stack). It returns the result value and any error. The expression can contain:

  • Variable references: item, item.title, items[0]
  • Comparison: ==, !=, <, >, <=, >=, === (same as ==, for convenience)
  • Boolean operations: &&, ||, !
  • Function calls: len(items), isActive(v)
  • Literals: 42, "text", true, false

type FuncMap

type FuncMap map[string]any

FuncMap is a map of function names to functions, similar to text/template's FuncMap. Functions can have any number of parameters and must return 1 or 2 values. If 2 values are returned, the second must be an error.

Functions can optionally take *VueContext as the first parameter:

func myFunc(ctx *VueContext, arg1 string) (string, error) { ... }
func myFunc(arg1 string) string { ... }  // without context

This allows access to the execution context.

type LessProcessor

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

LessProcessor implements vuego.NodeProcessor.

It implements the functionality to compile Less CSS to standard css. It processes `script` tags with a `type="text/css+less"` attribute.

func NewLessProcessor

func NewLessProcessor(fsys ...fs.FS) *LessProcessor

NewLessProcessor creates a new LESS processor.

func (*LessProcessor) New

func (lp *LessProcessor) New() NodeProcessor

New creates a new allocation of *LessProcessor.

func (*LessProcessor) PostProcess

func (lp *LessProcessor) PostProcess(nodes []*html.Node) error

PostProcess walks the DOM tree and performs compilation.

func (*LessProcessor) PreProcess

func (lp *LessProcessor) PreProcess(nodes []*html.Node) error

PreProcess.

type LessProcessorError

type LessProcessorError struct {
	// Err is the underlying error from the LESS processor.
	Err error
	// Reason is a descriptive message about the LESS processing failure.
	Reason string
}

LessProcessorError wraps processing errors with context.

func (*LessProcessorError) Error

func (e *LessProcessorError) Error() string

type LoadOption

type LoadOption func(*Vue)

LoadOption is a functional option for configuring Load().

func WithFS added in v0.0.5

func WithFS(templateFS fs.FS) LoadOption

WithFS returns a LoadOption that sets the filesystem for template loading.

func WithFuncs added in v0.2.0

func WithFuncs(funcMap FuncMap) LoadOption

WithFuncs returns a LoadOption that merges custom template functions into the existing funcmap.

func WithLessProcessor

func WithLessProcessor() LoadOption

WithLessProcessor returns a LoadOption that registers a LESS processor

func WithProcessor

func WithProcessor(processor NodeProcessor) LoadOption

WithProcessor returns a LoadOption that registers a custom node processor

type Loader

type Loader struct {
	// FS is the file system used to load templates.
	FS fs.FS
}

Loader loads and parses .vuego files from an fs.FS.

func NewLoader

func NewLoader(fs fs.FS) *Loader

NewLoader creates a Loader backed by fs.

func (*Loader) Load

func (l *Loader) Load(filename string) ([]*html.Node, error)

Load parses a full HTML document from the given filename.

func (*Loader) LoadFragment

func (l *Loader) LoadFragment(filename string) ([]*html.Node, error)

LoadFragment parses a template fragment; if the file is a full document, it falls back to Load. Front-matter is extracted and discarded; use loadFragment to access it.

func (*Loader) Stat

func (l *Loader) Stat(filename string) error

Stat checks that filename exists in the loader filesystem.

type NodeProcessor

type NodeProcessor interface {
	// New ensures that we can have render-scoped allocations.
	New() NodeProcessor

	// PreProcess receives the nodes as they are decoded.
	PreProcess(nodes []*html.Node) error

	// PostProcess receives the rendered nodes and may modify them in place.
	// It should return an error if processing fails.
	PostProcess(nodes []*html.Node) error
}

NodeProcessor is an interface for post-processing []*html.Node after template evaluation. Implementations can inspect and modify HTML nodes to implement custom tags and attributes. NodeProcessor receives the complete rendered DOM and can transform it in place.

Processors are called after all Vue directives and interpolations have been evaluated. Multiple processors can be registered and are applied in order of registration.

See docs/nodeprocessor.md for examples and best practices.

type Renderer

type Renderer interface {
	// Render renders HTML nodes to the given writer.
	Render(ctx context.Context, w io.Writer, nodes []*html.Node) error
}

Renderer renders parsed HTML nodes to output.

func NewRenderer

func NewRenderer() Renderer

NewRenderer creates a new Renderer.

type Stack

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

Stack provides stack-based variable lookup and convenient typed accessors.

func NewStack

func NewStack(root map[string]any) *Stack

NewStack constructs a Stack with an optional initial root map (nil allowed). The originalData parameter is the original value passed to Render (for struct field fallback).

func NewStackWithData

func NewStackWithData(root map[string]any, originalData any) *Stack

NewStackWithData constructs a Stack with both map data and original root data for struct field fallback.

func (*Stack) Copy added in v0.0.6

func (s *Stack) Copy() *Stack

Copy returns a copy of the stack that can be discarded. The root data is retained as is, the envmap is a copy.

func (*Stack) EnvMap

func (s *Stack) EnvMap() map[string]any

EnvMap converts the Stack to a map[string]any for expr evaluation. Includes all accessible values from stack and struct fields.

func (*Stack) ForEach

func (s *Stack) ForEach(expr string, fn func(index int, value any) error) error

ForEach iterates over a collection at the given expr and calls fn(index,value). Supports slices/arrays and map[string]any (iteration order for maps is unspecified). If fn returns an error iteration is stopped and the error passed through.

func (*Stack) GetInt

func (s *Stack) GetInt(expr string) (int, bool)

GetInt resolves and tries to return an int (best-effort).

func (*Stack) GetMap

func (s *Stack) GetMap(expr string) (map[string]any, bool)

GetMap returns map[string]any or converts map[string]string to map[string]any. Avoids reflection for other map types.

func (*Stack) GetSlice

func (s *Stack) GetSlice(expr string) ([]any, bool)

GetSlice returns a []any for slice types.

func (*Stack) GetString

func (s *Stack) GetString(expr string) (string, bool)

GetString resolves and tries to return a string.

func (*Stack) Lookup

func (s *Stack) Lookup(name string) (any, bool)

Lookup searches stack from top to bottom for a plain identifier (no dots). If not found in the stack maps, it checks the root data struct (if any). Returns (value, true) if found.

func (*Stack) Pop

func (s *Stack) Pop()

Pop the top-most Stack. If only root remains it still pops to empty slice safely. Returns pooled maps to reduce GC pressure.

func (*Stack) Push

func (s *Stack) Push(m map[string]any)

Push a new map as a top-most Stack. If m is nil, an empty map is obtained from the pool.

func (*Stack) Resolve

func (s *Stack) Resolve(expr string) (any, bool)

Resolve resolves dotted/bracketed expression paths like:

"user.name", "items[0].title", "mapKey.sub"

It returns (value, true) if resolution succeeded.

func (*Stack) Set

func (s *Stack) Set(key string, val any)

Set sets a key in the top-most Stack.

type Template

Template represents a prepared vuego template. It allows variable assignment and rendering with internal buffering.

func New added in v0.0.5

func New(opts ...LoadOption) Template

New creates a new Template for rendering strings, bytes, or readers without a filesystem. Use this when templates are provided as strings/bytes rather than loaded from files. To render from files, use NewFS(fs) or New(WithFS(fs)) instead. The returned Template can be used for variable assignment and rendering.

func NewFS added in v0.1.0

func NewFS(templateFS fs.FS, opts ...LoadOption) Template

NewFS creates a new Template with access to the given filesystem and optional configurations. The returned Template can be used to render files, strings, or bytes with variable assignment.

type TemplateConstructors added in v0.2.0

type TemplateConstructors interface {
	New() Template
	Load(filename string) Template
}

TemplateConstructors creates new template rendering contexts. The results provide request scoped data allocations and should be discarded after use.

type TemplateRendering added in v0.2.0

type TemplateRendering interface {
	Render(ctx context.Context, w io.Writer) error
	Layout(ctx context.Context, w io.Writer) error
}

TemplateRendering bundles the interface for the render functions.

type TemplateRenderingDetail added in v0.2.0

type TemplateRenderingDetail interface {
	RenderFile(ctx context.Context, w io.Writer, filename string) error
	RenderString(ctx context.Context, w io.Writer, templateStr string) error
	RenderByte(ctx context.Context, w io.Writer, templateData []byte) error
	RenderReader(ctx context.Context, w io.Writer, r io.Reader) error
}

TemplateRenderingDetail the interface for stateless render functions.

type TemplateState added in v0.2.0

type TemplateState interface {
	Fill(vars any) Template
	Assign(key string, value any) Template
	Get(key string) string
}

TemplateState bundles the interface for template state management.

type Vue

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

Vue is the main template renderer for .vuego templates. After initialization, Vue is safe for concurrent use by multiple goroutines.

func NewVue

func NewVue(templateFS fs.FS) *Vue

NewVue creates a new Vue backed by the given filesystem. The returned Vue is safe for concurrent use by multiple goroutines.

func (*Vue) DefaultFuncMap

func (v *Vue) DefaultFuncMap() FuncMap

DefaultFuncMap returns a FuncMap with built-in utility functions

func (*Vue) Funcs

func (v *Vue) Funcs(funcMap FuncMap) *Vue

Funcs merges custom template functions into the existing funcmap, overwriting any existing keys. Returns the Vue instance for chaining.

func (*Vue) RegisterNodeProcessor

func (v *Vue) RegisterNodeProcessor(processor NodeProcessor) *Vue

RegisterNodeProcessor adds a custom node processor to the Vue instance. Processors are applied in order after template evaluation completes.

func (*Vue) Render

func (v *Vue) Render(w io.Writer, filename string, data any) error

Render processes a full-page template file and writes the output to w. Front-matter data in the template is authoritative and overrides passed data. Render is safe to call concurrently from multiple goroutines.

func (*Vue) RenderFragment

func (v *Vue) RenderFragment(w io.Writer, filename string, data any) error

RenderFragment processes a template fragment file and writes the output to w. Front-matter data in the template is authoritative and overrides passed data. RenderFragment is safe to call concurrently from multiple goroutines.

func (*Vue) RenderNodes added in v0.2.0

func (v *Vue) RenderNodes(w io.Writer, nodes []*html.Node, data any) error

RenderNodes evaluates and renders HTML nodes with the given data. This is the core rendering function used by all public render methods.

type VueContext

type VueContext struct {

	// BaseDir is the root directory for template inclusion chains.
	BaseDir string
	// CurrentDir is the current working directory during template processing.
	CurrentDir string
	// FromFilename is the name of the file currently being processed.
	FromFilename string
	// TemplateStack is the stack of included template files.
	TemplateStack []string

	// TagStack is the stack of HTML tags being rendered.
	TagStack []string

	// Processors are the registered template processors.
	Processors []NodeProcessor
	// contains filtered or unexported fields
}

VueContext carries template inclusion context and request-scoped state used during evaluation. Each render operation gets its own VueContext, making concurrent rendering safe.

func NewVueContext

func NewVueContext(fromFilename string, options *VueContextOptions) VueContext

NewVueContext returns a VueContext initialized for the given template filename with initial data.

func (VueContext) CurrentTag

func (ctx VueContext) CurrentTag() string

CurrentTag returns the current parent tag, or empty string if no tag is on the stack.

func (VueContext) FormatTemplateChain

func (ctx VueContext) FormatTemplateChain() string

FormatTemplateChain returns the template inclusion chain formatted for error messages.

func (*VueContext) PopTag

func (ctx *VueContext) PopTag()

PopTag removes the current tag from the tag stack.

func (*VueContext) PushTag

func (ctx *VueContext) PushTag(tag string)

PushTag adds a tag to the tag stack.

func (VueContext) Stack added in v0.2.0

func (ctx VueContext) Stack() *Stack

Stack returns the variable resolution stack for this context. This allows functions with *VueContext parameters to resolve variables from the execution scope.

func (VueContext) WithTemplate

func (ctx VueContext) WithTemplate(filename string) VueContext

WithTemplate returns a copy of the context extended with filename in the inclusion chain.

type VueContextOptions

type VueContextOptions struct {
	// Stack is the resolver stack for variable lookups.
	Stack *Stack
	// Processors are the registered template processors.
	Processors []NodeProcessor
}

VueContextOptions holds configurable options for a new VueContext.

Directories

Path Synopsis
cmd
vuego command
internal
helpers
Package helpers provides HTML node manipulation utilities for vuego.
Package helpers provides HTML node manipulation utilities for vuego.
reflect
Package reflect provides utilities for traversing struct fields and values during template evaluation, supporting both field names and JSON tags.
Package reflect provides utilities for traversing struct fields and values during template evaluation, supporting both field names and JSON tags.

Jump to

Keyboard shortcuts

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