render

package
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Feb 24, 2026 License: MIT Imports: 11 Imported by: 0

Documentation

Overview

Package render provides server-side rendering (SSR) for Vango components.

The render package converts VNode trees into HTML strings or streams, handling all aspects of producing valid, secure HTML output including:

  • HTML5 compliant element rendering
  • Proper text and attribute escaping (XSS prevention)
  • Void element handling (input, br, img, etc.)
  • Boolean attribute handling (disabled, checked, etc.)
  • Hydration ID generation for client-side interactivity
  • Full page rendering with DOCTYPE, head, body
  • Thin client script injection

Basic Usage

To render a VNode tree to a string:

renderer := render.NewRenderer(render.RendererConfig{})
html, err := renderer.RenderToString(node)

To stream HTML to a writer:

renderer := render.NewRenderer(render.RendererConfig{})
err := renderer.RenderToWriter(w, node)

Full Page Rendering

To render a complete HTML document:

page := render.PageData{
    Body:       bodyNode,
    Title:      "My Page",
    SessionID:  session.ID,
    CSRFToken:  session.CSRFToken,
}
err := renderer.RenderPage(w, page)

Hydration IDs

Elements with event handlers automatically receive a data-hid attribute for client-side hydration. The handlers are collected during rendering and can be retrieved via GetHandlers().

Streaming

For large pages, use StreamingRenderer to flush content incrementally:

sr := render.NewStreamingRenderer(w, config)
err := sr.RenderPage(page)

Security

All text content is escaped by default to prevent XSS attacks. Raw HTML can be inserted using KindRaw nodes. By default, Vango sanitizes raw HTML sinks (drops on* attrs, sanitizes URL attrs, strips executable tags). To bypass sanitization, set URLPolicy.AllowUnsafeRawHTML=true, but only for fully trusted internal HTML.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type FlushableWriter

type FlushableWriter struct {
	io.Writer
	FlushCount int
}

FlushableWriter wraps an io.Writer with optional flushing capability. This is useful for testing streaming behavior without using http.ResponseWriter.

func (*FlushableWriter) Flush

func (w *FlushableWriter) Flush()

Flush implements http.Flusher.

type HookConfig

type HookConfig struct {
	Name   string // Hook name (e.g., "Sortable", "Tooltip")
	Config any    // Hook-specific configuration (struct or map, marshaled to JSON)
}

HookConfig contains configuration for a client-side hook.

type LinkTag

type LinkTag struct {
	Rel         string // rel attribute
	Href        string // href attribute
	Type        string // type attribute
	Sizes       string // sizes attribute
	CrossOrigin string // crossorigin attribute
	Media       string // media attribute
}

LinkTag represents a link element in the document head.

type MetaTag

type MetaTag struct {
	Name      string // name attribute
	Content   string // content attribute
	Property  string // property attribute (for OpenGraph)
	HTTPEquiv string // http-equiv attribute
	Charset   string // charset attribute
}

MetaTag represents a meta element in the document head.

type OptimisticConfig

type OptimisticConfig struct {
	Class string // Class to add/remove optimistically
	Text  string // Text to show optimistically
	Attr  string // Attribute to modify optimistically
	Value string // Attribute value
}

OptimisticConfig contains configuration for optimistic updates.

type PageData

type PageData struct {
	// Body is the root VNode for the page content
	Body *vdom.VNode

	// Title is the page title
	Title string

	// Meta contains meta tags for the page
	Meta []MetaTag

	// Links contains link tags (stylesheets, favicon, etc.)
	Links []LinkTag

	// Scripts contains script tags to include
	Scripts []ScriptTag

	// Styles contains inline CSS styles
	// SECURITY: Style content is treated as trusted and must not contain "</style>".
	// RenderPage rejects any style string containing a closing style tag to prevent HTML injection.
	Styles []string

	// SessionID is deprecated and no longer rendered.
	// The client manages session IDs via sessionStorage for WebSocket reconnection.
	// This field is retained for backward compatibility but has no effect.
	SessionID string

	// CSRFToken is rendered as a <meta name="csrf-token"> tag in the document head.
	// The client reads this for WebSocket handshake; userland code can also use it
	// for HTTP requests (e.g., fetch with X-CSRF-Token header).
	CSRFToken string

	// ClientScript is the path to the thin client JavaScript
	// Defaults to "/_vango/client.js" if not specified
	ClientScript string

	// StyleSheets contains paths to external stylesheets
	StyleSheets []string

	// Lang is the language attribute for the html element
	// Defaults to "en" if not specified
	Lang string

	// Debug enables debug mode for the thin client.
	// When true, adds data-debug="true" to the client script tag.
	// Should be false in production.
	Debug bool
}

PageData contains all data needed to render a complete HTML page.

type Renderer

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

Renderer handles server-side rendering of VNode trees to HTML.

func NewRenderer

func NewRenderer(config RendererConfig) *Renderer

NewRenderer creates a new Renderer with the given configuration.

func (*Renderer) GetHandlers

func (r *Renderer) GetHandlers() map[string]any

GetHandlers returns the handler registry collected during rendering. The map keys are in the format "hid_eventname" (e.g., "h1_onclick").

func (*Renderer) RenderPage

func (r *Renderer) RenderPage(w io.Writer, page PageData) error

RenderPage renders a complete HTML document to the given writer.

func (*Renderer) RenderToString

func (r *Renderer) RenderToString(node *vdom.VNode) (string, error)

RenderToString renders a VNode tree to a complete HTML string.

func (*Renderer) RenderToWriter

func (r *Renderer) RenderToWriter(w io.Writer, node *vdom.VNode) error

RenderToWriter streams a VNode tree to the given writer.

func (*Renderer) Reset

func (r *Renderer) Reset()

Reset resets the renderer state for reuse. This clears the HID counter and handler registry.

type RendererConfig

type RendererConfig struct {
	// Pretty enables pretty-printed HTML output with indentation.
	// Should only be used in development as it increases output size.
	Pretty bool

	// Indent is the string used for each indentation level in pretty mode.
	// Defaults to two spaces if not specified.
	Indent string

	// IncludeCSRF indicates whether to include CSRF token in the output.
	IncludeCSRF bool

	// AssetPath is the base path for assets.
	AssetPath string

	// InlineCriticalCSS indicates whether to inline critical CSS.
	InlineCriticalCSS bool

	// URLPolicy controls scheme allowlists for URL-bearing attributes.
	// If zero-valued, defaults are used.
	URLPolicy vdom.URLPolicy
}

RendererConfig configures the HTML renderer.

type ScriptTag

type ScriptTag struct {
	Src    string // src attribute
	Type   string // type attribute
	Defer  bool   // defer attribute
	Async  bool   // async attribute
	Module bool   // type="module"
	Inline string // inline script content
}

ScriptTag represents a script element.

type StreamingRenderer

type StreamingRenderer struct {
	*Renderer
	// contains filtered or unexported fields
}

StreamingRenderer wraps Renderer with chunked output support. It flushes content incrementally for faster time-to-first-byte.

func NewStreamingRenderer

func NewStreamingRenderer(w http.ResponseWriter, config RendererConfig) *StreamingRenderer

NewStreamingRenderer creates a streaming renderer that writes to an http.ResponseWriter. If the writer implements http.Flusher, content will be flushed after each section for faster TTFB.

func (*StreamingRenderer) RenderPage

func (s *StreamingRenderer) RenderPage(page PageData) error

RenderPage renders a complete HTML document with incremental flushing. The head section is flushed immediately for faster first paint.

Jump to

Keyboard shortcuts

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