gox

package
v0.4.13 Latest Latest
Warning

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

Go to latest
Published: Nov 12, 2026 License: MIT Imports: 30 Imported by: 0 modules, 0 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

GoX

GoX combines EVM Go code and HTML. Each renderer is a named Go function with an explicit first *gox.Builder argument. .go and .gox files share one package; functions can call each other in either direction. Parameters normally occupy separate lines, with trailing commas.

func Customers(
    b *gox.Builder,
    page *Page,
    customers []*Customer,
) {
    heading := fmt.Sprintf("%s (%d)", page.Title, len(customers))
    <section>
        <h1>
            heading
        </h1>
        <ul>
            for _, customer := range customers {
                <li>
                    customer.Name
                </li>
            }
        </ul>
    </section>
}

func countLabel(n int) string { return fmt.Sprintf("%d", n) }

Syntax

  • Put markup at the first non-whitespace < on a line. Strings and Go comments protect their contents; multiline opening tags continue through >.
  • Inside elements/fragments, standalone expressions render. Assignments, conditions and arguments do not. Outside them, write ordinary Go.
  • Quote text. Source indentation emits nothing; string whitespace is preserved. Use <p>{name}</p> for inline values and {"{"} for a literal brace.
  • Attributes accept quoted strings with interpolation or {expression}. Boolean HTML attributes omit false; ARIA attributes retain it.
  • JS/CSS bodies retain their syntax. Insert Go data with {=expression}.
  • Inputs are typed. Inside markup, omitted arguments bind by name; explicit inputs win and incompatible matching types fail compilation.
  • KVO selectors use model aliases. Go fields also accept unambiguous JSON names and snake_case (AppIDs → app_ids, URLs → urls).

GoX lowers markup before Go parsing, then uses EVM's compiler and budgets. HTML, text and CSS share that pipeline but use different escaping contexts.

Use a fragment for output that needs no HTML element:

func Greeting(b *gox.Builder, name string) {
    <>
        "Hello, "
        name
        "!"
    </>
}

Fragments must balance within each branch, loop iteration and component. They do not create a Go variable scope; use a Go block for that. Inside an element, attribute helpers called through a fragment still modify that element's pending opening tag. <>...</> also works in text and CSS templates.

tmpl, err := gox.Compile("greeting.gox", `func Greeting(b *gox.Builder, name string) {
    <p>
        "Hello, "
        name
        "!"
    </p>
}`)
if err != nil {
    return err
}
program, err := tmpl.Link()
if err != nil {
    return err
}
html, err := program.Render(ctx, []values.Value{
    values.String("Alice & Bob"),
}, gox.RenderOptions{Strict: true})
// html == "<p>Hello, Alice &amp; Bob!</p>"

Compile accepts the same evm.Package descriptions as EVM's compiler. Link accepts their implementations; the two sets must have compatible signatures. The standard library and supplied packages autoimport by package basename, including fmt. No package or import declaration is needed in a GoX file.

Template.Parameters gives the entry argument order. Arguments use the existing EVM value ABI, including host types, script structs and KVO models. Compiled Module, original source positions, GeneratedSources and class metadata are available for tooling. Keep the template's rendering plan with its module.

A linked Program supports concurrent renders. Each render gets isolated VM globals and builder state; registered host implementations retain their own state. Context cancellation and RenderOptions.Budget apply to execution. Output is capped at 16 MiB by default (MaxOutputBytes overrides it). Failed renders return an error and no partial document.

Ambient context

evmruntime.Ambient is a persistent map of string to any. A nil pointer is an empty context. Get(key) searches from the newest node to its parents; CloneWith(map[string]any{...}) copies a delta map and shares its parent. An explicit nil value hides the parent value. Stored values are not deep-copied. Values() returns a separate flattened map for interop with older extras APIs.

Pass it as an ordinary optional parameter, usually ambient *evmruntime.Ambient. Calls inside tags and fragments inherit it by name like other parameters. A local override can use ambient = ambient.CloneWith(...); callers keep their original context.

Components, slots and helpers

CompileSources(sources, packages...) compiles a map of filenames to source text. Call program.RenderFunc(ctx, "Page", args, options) to select a renderer; args omits the builder. CompileFiles(entry, sources, ...) also selects a default renderer for Render: entry can be a function name or a GoX filename (its first renderer). Ordinary Go files require their own imports. GoX files autoimport registered packages. An omitted package declaration inherits the package name from the other files, defaulting to plugin.

Function names identify components: func Button(...) is <Button>; func EarnCard(...) is <EarnCard>. They also work as ordinary function values: chosen := Button, Button(...) or <chosen ... />. Tags resolve exact, case-sensitive Go names, including lexical function values and selectors such as <ui.Button> or <card.Render>. Component attributes keep parameter spelling, including camelCase. A callable in scope takes precedence over a same-named HTML tag; prefer capitalized component names to avoid collisions. Unknown capitalized tags are compile errors. The full Go signature includes the builder and every input. See the tested page and button.

Compile, CompileFiles and CompileSources use the same compiler. Every renderer declares its function name, builder and inputs; anonymous parameter-list templates are not supported.

<Button label={customer.Name}>
    <slot-body>
        "Hello, "
        customer.Name
    </slot-body>
    <slot-after>
        <span>{page.Title}</span>
    </slot-after>
</Button>

The button declares body func() and after func() inputs and calls body() and after(). Children without <slot-...> wrappers supply body. A slot typed func(item *Item) exposes item inside that slot, while retaining access to the caller's lexical variables. Repeated or unknown inputs are compile errors.

Local components use Go closures:

item := func(label string) {
    <strong>
        page.Title
        ": "
        label
    </strong>
}
<div>
    item("one")
    <item label="two" />
</div>

For ordinary calls, explicit positional arguments come first and omitted trailing arguments are filled by name. Component attributes supply named arguments. The builder argument is inserted automatically when the signature requests one. Rendering functions containing markup return no values. Ordinary helpers can return values, including gox.HTML; output-position calls render their result. Use _ = helper() to discard a value deliberately.

func decorate(b *gox.Builder, disabled bool) {
    b.Class("button")
    b.Attr("aria-disabled", disabled)
    b.Attr("disabled", disabled)
}

Call decorate(disabled) inside a pending opening tag. class("...") appends classes; other attributes replace the earlier value. Adding attributes after child output fails. b.Open, b.Close, b.Text and b.HTML support native-style render helpers. The builder is valid only during its render. It cannot write HTML text into a JavaScript, CSS, or attribute context through a hidden callback.

value | format means format(value); value | format(arg) means format(arg, value). Integer bitwise OR keeps its Go meaning. Pipelines require a callable right side and a single result.

Whitespace and output formats

Indentation and newlines between Go/markup statements emit nothing. Add spaces and newlines explicitly in strings. Raw strings preserve their contents, useful inside <pre>:

<pre>
    "first\n  second\n"
</pre>

Inline JS/CSS retain their native source whitespace and use {=value} for data:

<script>const customer = {=customer};</script>
<style>.button { color: {=color}; }</style>

There is no automatic pretty-print mode: it could change inline text or <pre> semantics. Options{Format: TextFormat} renders top-level expressions as plain text. CSSFormat treats literal strings as CSS source and dynamically rendered expressions as contextually escaped CSS data. Both use the same Go frontend, type analysis, nil guards and EVM compiler; HTML markup requires HTMLFormat.

Safety and failures

The contextual analyzer and escaping functions are copied from Go's html/template; see upstream notes. Compilation chooses filters for HTML text, attributes, URLs, srcsets, JavaScript and CSS. Runtime calls those filters directly; it never executes a Go template. The copied upstream tests and end-to-end comparisons cover the escaping behavior.

Template source and host packages are trusted code. Data is untrusted. gox.HTML, CSS, JS, JSStr, URL and Srcset have Go's explicit trusted-content semantics; converting untrusted data to one of these types bypasses protection. Dynamic script/style types are rejected. Runtime attribute helpers cannot change those types or meta-refresh parsing. Their other attribute names and values pass contextual validation. Rendering operations also check their input context at runtime to prevent callbacks from bypassing the compiled filters.

Nil pointer field accesses in output expressions report a Diagnostic and skip that expression or component call. Attribute failures omit the whole attribute. Inline JS/CSS use a context-safe empty/null replacement so omission cannot join unsafe tokens. Guards preserve operand order and short-circuiting without defers. Strict: true turns these failures into render errors; other EVM errors always fail the render. Report defaults to slog.Warn and can be replaced by the host. This does not recover arbitrary host panics or silently swallow script failures.

Branches, loop iterations and components must contain complete elements. return, break and continue close elements they leave. Labeled jumps across open elements are rejected. Malformed syntax, incompatible input types and ambiguous escaping contexts fail compilation with source positions.

Class discovery

Template.Classes includes static class attributes, constant interpolations and constant arguments to class, Class and attr("class", ...), with source positions. bg-{tone} is dynamic and does not falsely contribute bg-. DynamicClasses flags values that need a separate Tailwind safelist or host policy. Arbitrary host helper output cannot be enumerated by this compiler.

Validation

go test ./...
go test -race ./gox/... ./evm/...
go test ./gox -run '^$' -fuzz FuzzCompileGoX -fuzztime=15s
go test ./gox -run '^$' -bench BenchmarkApplication -benchmem -benchtime=200ms -count=8

The application benchmarks use anonymized production-derived card, history and comparison templates, each at two sizes. Both engines render identical output to immutable strings using reused buffers. Compilation, linking and view-model preparation are excluded.

On Apple M5 Max with Go 1.27.3, GoX uses 27–40% less execution time than cached html/template across these six workloads (eight samples, 2026-11-06). The report includes allocation counts, before/after samples, EVM regression controls and reproduction commands. BenchmarkRender remains a small diagnostic workload.

Documentation

Overview

Package gox compiles GoX templates into typed EVM functions.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func BuilderType

func BuilderType() *values.Type

func HTMLType

func HTMLType() *values.Type

func Package

func Package() evm.Package

Package declares and binds the rendering API for mixed EVM packages.

Types

type Builder

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

Builder is the render-scoped capability supplied implicitly to GoX helpers. Its opening tag remains mutable until the first child output. Do not retain it after a render or use it concurrently.

func (*Builder) Attr

func (b *Builder) Attr(name string, value any) error

func (*Builder) Class

func (b *Builder) Class(value string) error

func (*Builder) Close

func (b *Builder) Close() error

func (*Builder) HTML

func (b *Builder) HTML(value HTML) error

func (*Builder) Open

func (b *Builder) Open(name string) error

Open and Close support rendering helpers written against the builder directly. Raw script/style bodies need the compiler's contextual analysis or trusted HTML.

func (*Builder) Text

func (b *Builder) Text(value string) error

type CSS

type CSS = ht.CSS

type Class

type Class struct {
	Name     string
	Position evm.SourcePosition
}

Class identifies a statically known CSS class, including classes in helpers.

type Diagnostic

type Diagnostic struct {
	Position evm.SourcePosition
	Message  string
}

func (Diagnostic) Error

func (d Diagnostic) Error() string

type Format

type Format uint8

Format selects output analysis at compile time.

const (
	HTMLFormat Format = iota
	TextFormat
	CSSFormat
)

type HTML

type HTML = ht.HTML

Trusted content types bypass selected escaping steps. Only construct them from trusted source, never by casting unvalidated input.

type JS

type JS = ht.JS

type JSStr

type JSStr = ht.JSStr

type Options

type Options struct{ Format Format }

Options fixes the output language during compilation. The zero value is HTML.

func (Options) Compile

func (o Options) Compile(filename, source string, packages ...evm.Package) (*Template, error)

func (Options) CompileFiles

func (options Options) CompileFiles(entry string, sources map[string]string, packages ...evm.Package) (*Template, error)

func (Options) CompileSources

func (options Options) CompileSources(sources map[string]string, packages ...evm.Package) (*Template, error)

type Parameter

type Parameter struct{ Name, Type string }

Parameter describes an entry input in Render argument order.

type Program

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

Program binds a template to host implementations and supports concurrent renders.

func (*Program) EVM

func (p *Program) EVM() *evm.Program

EVM returns the linked program for ordinary Go entry points in this package.

func (*Program) Render

func (p *Program) Render(ctx context.Context, args []values.Value, options RenderOptions) (string, error)

Render executes with EVM values in Parameters order. Globals and temporary state reset between renders. Host package implementations retain their own state.

func (*Program) RenderFunc

func (p *Program) RenderFunc(ctx context.Context, name string, args []values.Value, options RenderOptions) (string, error)

RenderFunc executes a named renderer. args excludes its explicit builder parameter.

type RenderOptions

type RenderOptions struct {
	// Strict fails on nil field access in output instead of reporting and omitting it.
	Strict bool
	// Report receives recoverable output diagnostics. Nil logs through slog.
	Report func(Diagnostic)
	// Budget applies the same execution limits as an EVM script.
	Budget evm.Budget
	// MaxOutputBytes defaults to 16 MiB. A failed render returns no partial output.
	MaxOutputBytes int
}

type Srcset

type Srcset = ht.Srcset

type Template

type Template struct {
	Entry            string
	GeneratedSources map[string]string
	DynamicClasses   bool

	Module          *evm.Module
	Parameters      []Parameter
	Classes         []Class
	GeneratedSource string
	// contains filtered or unexported fields
}

Template holds bytecode and its immutable rendering plan. Keep the plan with the module; the module alone does not contain the contextual escaping filters. Treat exported metadata as read-only after compilation.

func Compile

func Compile(filename, source string, packages ...evm.Package) (*Template, error)

Compile compiles an HTML GoX file using EVM's standard and supplied packages.

Example
package main

import (
	"context"
	"fmt"

	"github.com/andreyvit/edb/gox"
	"github.com/andreyvit/edb/values"
)

func main() {
	tmpl, err := gox.Compile("greeting.gox", `func Greeting(b *gox.Builder, name string) {
    <p>
        "Hello, "
        name
        "!"
    </p>
}`)
	if err != nil {
		panic(err)
	}
	program, err := tmpl.Link()
	if err != nil {
		panic(err)
	}
	output, err := program.Render(context.Background(), []values.Value{
		values.String("Alice & Bob"),
	}, gox.RenderOptions{Strict: true})
	if err != nil {
		panic(err)
	}
	fmt.Println(output)
}
Output:
<p>Hello, Alice &amp; Bob!</p>

func CompileFiles

func CompileFiles(entry string, sources map[string]string, packages ...evm.Package) (*Template, error)

CompileFiles compiles one package and selects the default renderer by function name or filename. Component tags use exact Go callable names.

func CompileSources

func CompileSources(sources map[string]string, packages ...evm.Package) (*Template, error)

CompileSources compiles ordinary Go and GoX files into one package. Each GoX renderer declares its name and builder parameter. Use RenderFunc to select one.

func (t *Template) Link(packages ...evm.Package) (*Program, error)

Link binds the module to host packages with matching signatures. It does not run it.

type URL

type URL = ht.URL

Directories

Path Synopsis
internal

Jump to

Keyboard shortcuts

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