vuego

package module
v0.11.0 Latest Latest
Warning

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

Go to latest
Published: Sep 29, 2026 License: MIT Imports: 28 Imported by: 5 modules, 14 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Vuego - A Go based VueJS syntax template engine

Go Reference Coverage

Vuego brings a Vue.js-inspired template engine to Go. Render HTML templates in familiar Vue syntax, with no JavaScript runtime.

You can try Vuego:

The Vuego CLI also ships as a docker image, which runs the tour.

About

Vuego renders templates on the server. Its runtime picks up template edits while the application keeps running. It carries composition and layouts, and aims to serve as the single runtime for a codebase that writes Go on both the front end and the back end.

The choices Vuego makes:

  • A VueJS-compatible syntax covering v-if, v-for and interpolation
  • Composition with the usage of the html <template> tag (unique syntax)
  • DOM driven templating, type safety based on generics and reflection
  • YAML/JSON as the default way to provide template view rendering

A machine readable data format lets vuego support the development lifecycle through the vuego-cli tool, which runs a development playground. Three steps:

  • start vuego-cli serve ./templates
  • edit .json and .vuego files
  • refresh to view changes

The project remains under active development. The API surface may still shift as feedback and observations arrive. Each release carries a tag.

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.

// load your templates from a folder.
// the argument can be swapped for an embed.FS value.
renderer := vuego.NewFS(os.DirFS("templates"))

if err := renderer.File(filename).Fill(data).Render(r.Context(), w); err != nil {
	return err
}

You can provide your own type safe wrappers:

func (v *Views) IndexView(data IndexData) vuego.Template {
	return vuego.View[IndexData](v.renderer, "index.vuego", data)
}

And you don't need to chain the functions:

renderer := vuego.NewFS(embedFS)

tpl := renderer.New()
tpl.Fill(data)
tpl.Assign("meta", meta)
err := tpl.Render(ctx, out)

If you want to render from a string and not a filesystem:

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

For more detail on authoring vuego templates, check the documentation:

Vuego CLI

With titpetric/vuego-cli you can do the following:

  • vuego-cli serve <folder> - load a development server for templates,
  • vuego-cli tour <folder> - load a learning tour of vuego,
  • vuego-cli docs <folder> - load a documentation server.

Beside those learning tools, separate commands fmt, lint and render files.

Documentation

The Template Syntax reference covers four main areas:

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

Further resources:

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GetSlotName added in v0.5.0

func GetSlotName(attr string) string

GetSlotName extracts the slot name from a v-slot directive. A directive naming none yields "default".

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 maps template function names to functions, as text/template does. A function takes any number of parameters and returns one value, or a value and an error. An optional first parameter of *VueContext or context.Context receives the execution context. See docs/funcmap.md.

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 does nothing. PostProcess carries the compile.

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

Error returns the combined reason and underlying error message.

type LoadOption

type LoadOption func(*Vue)

LoadOption is a functional option for configuring Load().

func WithComponents added in v0.5.0

func WithComponents() LoadOption

WithComponents returns a LoadOption that registers every component shorthand. It walks the components folder and its subfolders for .vuego files, turning each path into a kebab-case tag name from the directory and the filename.

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, falling back to Load for a full document. It strips the front matter and drops it; loadFragment returns 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 OverlayFS added in v0.7.4

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

OverlayFS overlays two filesystems.

This allows extension of the lower filesystem with modified files, new files and encourages composition of the contents of a `fs.FS`.

func NewOverlayFS added in v0.7.4

func NewOverlayFS(upper fs.FS, lower ...fs.FS) *OverlayFS

NewOverlayFS will create a new *OverlayFS.

func (*OverlayFS) Glob added in v0.7.4

func (o *OverlayFS) Glob(pattern string) ([]string, error)

Glob implements combined FS reading.

func (*OverlayFS) Open added in v0.7.4

func (o *OverlayFS) Open(name string) (fs.File, error)

Open opens a file in the overlaid filesystem.

func (*OverlayFS) ReadDir added in v0.7.4

func (o *OverlayFS) ReadDir(name string) ([]fs.DirEntry, error)

ReadDir implements combined FS reading.

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 SlotContent added in v0.5.0

type SlotContent struct {
	// Nodes contains the rendered content for this slot.
	Nodes []*html.Node
	// Props contains any scoped props passed to the slot.
	Props map[string]any
	// TemplateNode holds the original template node for processing scoped slots.
	TemplateNode *html.Node
}

SlotContent holds the processed content for a slot along with any scoped props.

type SlotScope added in v0.5.0

type SlotScope struct {
	// Slots maps slot names to their content.
	// Empty string key is the default slot.
	Slots map[string]*SlotContent
}

SlotScope holds all slot contents indexed by name for a component instance.

func NewSlotScope added in v0.5.0

func NewSlotScope() *SlotScope

NewSlotScope creates a new SlotScope for a component.

func (*SlotScope) GetSlot added in v0.5.0

func (ss *SlotScope) GetSlot(name string) *SlotContent

GetSlot retrieves slot content by name. Returns nil if the slot doesn't exist.

func (*SlotScope) SetSlot added in v0.5.0

func (ss *SlotScope) SetSlot(name string, content *SlotContent)

SetSlot sets the content for a named slot.

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 over an optional root map; nil yields an empty one. It records no original data, so it carries no 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 throwaway copy of the stack. It keeps the root data and flattens the scopes into a fresh map.

Copy flattens without touching envCache. Every goroutine calling Load on a base template reads that template's stack, so a write to the cache there races.

func (*Stack) EnvMap

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

EnvMap converts the Stack to a map[string]any for expr evaluation, holding every value the scopes and the struct fields reach. It caches the result and hands the same map back until Push, Pop or Set invalidates it.

EnvMap serves a request-scoped stack, which one goroutine owns; the cache carries no mutex. Call Copy to read a stack another goroutine may hold.

func (*Stack) ForEach

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

ForEach walks the collection at expr and calls fn(index, value) for each element. It accepts slices, arrays and maps; a map walks in no set order. An error from fn stops the walk and reaches the caller unchanged.

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 discards the top-most scope. Popping the last one leaves an empty scope behind rather than an empty slice. The discarded map returns to the pool.

func (*Stack) Push

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

Push adds m as the top-most scope. A nil m takes an empty map from the pool instead.

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 Template that renders strings, bytes or readers without a filesystem. Call NewFS(fs) or New(WithFS(fs)) to render files instead. The returned Template holds assigned variables and renders them.

func NewFS added in v0.1.0

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

NewFS creates a Template over the given filesystem, applying each option in order. The returned Template renders files, strings or bytes and holds assigned variables.

func View added in v0.7.1

func View[V any](renderer Template, filename string, data V) Template

View binds a template file to a data model type. Render the returned template once, then discard it.

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
}

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 Vue over the given filesystem. Goroutines may share the returned Vue concurrently once it stops changing.

func (*Vue) DefaultFuncMap

func (v *Vue) DefaultFuncMap() FuncMap

DefaultFuncMap returns the built-in template functions. docs/funcmap.md documents every key.

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) GetComponentFile added in v0.5.0

func (v *Vue) GetComponentFile(tagName string) (string, bool)

GetComponentFile looks up a component file by its kebab-case tag name. Returns the filename and true if found, otherwise returns empty string and false.

func (*Vue) RegisterComponent added in v0.5.0

func (v *Vue) RegisterComponent(tagName, filename string) *Vue

RegisterComponent registers a component shorthand mapping, so a tagName of "button-primary" resolves to a filename of "components/ButtonPrimary.vuego".

func (*Vue) RegisterNodeProcessor

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

RegisterNodeProcessor adds a custom node processor to the Vue instance. Each processor runs in registration order once template evaluation ends.

func (*Vue) Render

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

Render processes a full-page template file and writes the output to w. Front matter in the template wins over the data the caller hands in. Goroutines may call Render concurrently.

func (*Vue) RenderFragment

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

RenderFragment processes a template fragment file and writes the output to w. Front matter in the template wins over the data the caller hands in. Goroutines may call RenderFragment concurrently.

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

	// SlotScope contains slot content for the current component.
	SlotScope *SlotScope
	// 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(ctx context.Context, fromFilename string, options *VueContextOptions) VueContext

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

func (VueContext) Context added in v0.9.4

func (ctx VueContext) Context() context.Context

Context returns the context.Context associated with this VueContext.

func (VueContext) CurrentTag

func (ctx VueContext) CurrentTag() string

CurrentTag returns the current parent tag, or the empty string when the tag stack holds none.

func (VueContext) ExprEnv added in v0.9.4

func (ctx VueContext) ExprEnv() map[string]any

ExprEnv returns the env map for expr evaluation. It wraps each function taking a context.Context first, so a template calls it without one and the wrapper supplies the render context.

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
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.
Package markdown parses GFM-flavoured markdown and renders each element through vuego templates.
Package markdown parses GFM-flavoured markdown and renders each element through vuego templates.
tests
assert
Minimalistic drop in eplacement for testing/assert
Minimalistic drop in eplacement for testing/assert

Jump to

Keyboard shortcuts

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