context

package
v0.9.0 Latest Latest
Warning

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

Go to latest
Published: May 12, 2026 License: MIT Imports: 7 Imported by: 0

Documentation

Overview

Package context provides template execution context utilities for the LiveTemplate library. It handles the "lvt" namespace in templates, providing access to validation errors, flash messages, and development mode flags.

Index

Examples

Constants

View Source
const FlashPrefix = "_flash:"

FlashPrefix is the prefix used to identify flash messages in the unified messages map. Flash messages are stored as "_flash:key" -> "message" in the map. This allows a single map to contain both field errors and flash messages.

View Source
const (
	// TemplateContextKey is the key used to access lvt context in templates
	TemplateContextKey = "lvt"
)

Variables

This section is empty.

Functions

func AddLvtToData added in v0.2.0

func AddLvtToData(data interface{}, messages map[string]string, devMode bool, uploadRegistry ...interface{}) interface{}

AddLvtToData converts data to include lvt context for template execution. This is a convenience wrapper around BuildDataMap for backward compatibility.

func BuildDataMap added in v0.8.5

func BuildDataMap(data interface{}, messages map[string]string, devMode bool, uploadRegistry interface{}) interface{}

BuildDataMap creates a template data map with lvt context from the given data. This is the single source of truth for data→map conversion, used by both template execution and tree building to avoid duplicate reflection.

For struct data, exported zero-arg methods are eagerly evaluated and their return values stored in the map. This differs from html/template's lazy dispatch — all qualifying methods run on every call, even if the template doesn't reference them. Avoid methods with side effects or expensive computations in State types.

func ExecuteTemplateWithContext

func ExecuteTemplateWithContext(tmpl *template.Template, data interface{}, messages map[string]string, devMode bool, uploadRegistry interface{}) ([]byte, error)

ExecuteTemplateWithContext adds lvt context to template execution by augmenting the data.

This function handles different types of input data:

  • Structs: Fields are copied to a map, using json tags if present
  • Maps: Keys are copied to template data
  • Nil pointers: Only lvt context is provided
  • Primitives: Passed directly to the template as-is (lvt not available)

The lvt context is available in templates via {{.lvt}} for structs, maps, and nil pointers. For primitive types (string, int, bool, etc.), lvt context is not available to maintain compatibility with standard Go templates.

The messages map contains both field errors and flash messages. Flash messages are identified by the "_flash:" prefix (e.g., "_flash:success" -> "Changes saved!"). Field errors affect ResponseMetadata.Success; flash messages don't.

Note: If struct fields or map keys conflict with the reserved "lvt" key, they will be skipped to ensure the lvt context remains accessible in templates.

Example
type User struct {
	Name  string
	Email string
}

tmplStr := `Name: {{.Name}}
{{if .lvt.HasError "Email"}}Error: {{.lvt.Error "Email"}}{{end}}`

tmpl, _ := template.New("user").Parse(tmplStr)
data := User{Name: "John", Email: "invalid"}
errors := map[string]string{"Email": "Invalid format"}

result, _ := ExecuteTemplateWithContext(tmpl, data, errors, false, nil)
_ = result

func ExecuteTemplateWithDataMap added in v0.8.5

func ExecuteTemplateWithDataMap(tmpl *template.Template, dataMap interface{}) ([]byte, error)

ExecuteTemplateWithDataMap executes a template with a pre-built data map. Use this when the data map has already been constructed via BuildDataMap to avoid duplicate reflection.

Types

type TemplateContext

type TemplateContext struct {
	DevMode bool // Development mode - use local client library instead of CDN
	// contains filtered or unexported fields
}

TemplateContext provides utility functions for templates via the lvt namespace.

It provides two separate message systems via a unified messages map:

  • Errors: Field validation errors from action dispatch (affects ResponseMetadata.Success)
  • Flash: Page-level messages (prefixed with "_flash:") that don't affect Success

Thread-safety: TemplateContext is safe for concurrent reads but not for concurrent writes. If you need to share a TemplateContext across goroutines that modify it, external synchronization is required. In typical usage, each template execution creates a new TemplateContext, so concurrent access is not an issue.

func NewTemplateContext

func NewTemplateContext(messages map[string]string, devMode bool) *TemplateContext

NewTemplateContext creates a new TemplateContext with the given messages map and devMode flag.

The messages map contains both field errors and flash messages. Flash messages are identified by the "_flash:" prefix (e.g., "_flash:success" -> "Changes saved!").

The messages map is stored by reference, not copied. Callers should not modify the map after passing it to NewTemplateContext.

Example
errors := map[string]string{
	"email": "Invalid email format",
	"name":  "Name is required",
}
ctx := NewTemplateContext(errors, true)

if ctx.HasError("email") {
	println(ctx.Error("email"))
}

func (*TemplateContext) AllErrors

func (t *TemplateContext) AllErrors() map[string]string

AllErrors returns a copy of all field errors (excludes flash messages). The returned map is a defensive copy and mutations will not affect internal state.

func (*TemplateContext) AllFlash added in v0.7.7

func (t *TemplateContext) AllFlash() map[string]string

AllFlash returns a copy of all flash messages (with prefix stripped). The returned map is a defensive copy and mutations will not affect internal state.

func (*TemplateContext) AriaDisabled added in v0.8.14

func (t *TemplateContext) AriaDisabled(fields ...string) template.HTMLAttr

AriaDisabled returns aria-disabled="true" if any of the given fields have an error. Returns empty template.HTMLAttr if no errors exist for any listed field.

Use this on related UI elements (e.g. submit buttons) that should appear disabled while validation errors are present — not on the errored field itself. For marking errored fields, use AriaInvalid instead.

Note: aria-disabled signals a disabled state to assistive technology but does not prevent interaction. Pair with the HTML disabled attribute or JavaScript to actually block form submission.

func (*TemplateContext) AriaInvalid added in v0.8.12

func (t *TemplateContext) AriaInvalid(field string) template.HTMLAttr

AriaInvalid returns aria-invalid="true" as template.HTMLAttr if the field has an error. Returns empty template.HTMLAttr if no error exists.

func (*TemplateContext) Error

func (t *TemplateContext) Error(field string) string

Error returns the error message for a field. Returns empty string if the field has no error, if messages map is nil, or if the field is a flash message key (use Flash() for those).

func (*TemplateContext) ErrorTag added in v0.8.12

func (t *TemplateContext) ErrorTag(field string) template.HTML

ErrorTag returns the error message wrapped in a <small> element as template.HTML. Returns empty template.HTML if the field has no error. The error message text is HTML-escaped to prevent XSS.

func (*TemplateContext) Flash added in v0.7.7

func (t *TemplateContext) Flash(key string) string

Flash returns the flash message for a key. Returns empty string if the key has no flash message or if messages map is nil. Common keys: "success", "error", "info", "warning"

func (*TemplateContext) FlashTag added in v0.8.14

func (t *TemplateContext) FlashTag(key string) template.HTML

FlashTag returns the flash message wrapped in an <output> element as template.HTML. Returns empty template.HTML if the key has no flash message. Uses role="alert" for "error" key and role="status" for all other keys. The flash message text is HTML-escaped to prevent XSS.

func (*TemplateContext) HasAnyError

func (t *TemplateContext) HasAnyError() bool

HasAnyError checks if any field errors exist (excludes flash messages). Returns false if messages map is nil or contains only flash messages.

func (*TemplateContext) HasAnyFlash added in v0.7.7

func (t *TemplateContext) HasAnyFlash() bool

HasAnyFlash checks if any flash messages exist. Returns false if messages map is nil or contains no flash messages.

func (*TemplateContext) HasError

func (t *TemplateContext) HasError(field string) bool

HasError checks if a field has an error. Returns false if messages map is nil or if the field is a flash message key.

func (*TemplateContext) HasFlash added in v0.7.7

func (t *TemplateContext) HasFlash(key string) bool

HasFlash checks if a key has a flash message. Returns false if messages map is nil.

func (*TemplateContext) HasUploadError added in v0.3.1

func (t *TemplateContext) HasUploadError(name string) bool

HasUploadError checks if any upload entry has an error for the given upload name.

func (*TemplateContext) SetUploadRegistry added in v0.3.1

func (t *TemplateContext) SetUploadRegistry(registry interface{})

SetUploadRegistry sets the upload registry for this template context. This allows templates to access upload state via .lvt.Uploads(name).

func (*TemplateContext) UploadError added in v0.3.1

func (t *TemplateContext) UploadError(name string) string

UploadError returns the first error message for the given upload name. Returns empty string if no errors exist.

func (*TemplateContext) Uploads added in v0.3.1

func (t *TemplateContext) Uploads(name string) interface{}

Uploads returns upload entries for a given upload name. Returns nil if no upload registry is set or upload doesn't exist. The upload registry is expected to have a method: GetUpload(name string) interface{} which returns an object with GetEntries() []interface{} method.

Jump to

Keyboard shortcuts

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