render

package module
v0.0.0-...-ffb1c48 Latest Latest
Warning

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

Go to latest
Published: Jan 6, 2026 License: MIT Imports: 14 Imported by: 0

Documentation

Overview

Package render provides HTML template rendering for the rig HTTP library.

It wraps Go's html/template package with a convenient API for web applications, supporting template caching, layouts, partials, hot reloading, custom functions, and content negotiation.

Basic Usage

engine := render.New(render.Config{
    Directory: "./templates",
})
r := rig.New()
r.Use(engine.Middleware())

r.GET("/", func(c *rig.Context) error {
    return render.HTML(c, http.StatusOK, "home", map[string]any{
        "Title": "Welcome",
    })
})

With Layouts

engine := render.New(render.Config{
    Directory: "./templates",
    Layout:    "layouts/base",
})

Templates can use {{.Content}} to include the page content.

Partials

Files starting with underscore (e.g., _sidebar.html) are partials. They are automatically available to all templates:

{{template "_sidebar" .}}

Shared Directories (Component-Based Architecture)

For larger applications, use SharedDirs to designate entire directories as globally available partials. This enables component-based architecture:

engine := render.New(render.Config{
    Directory: "./templates",
    Layout:    "layouts/base",
    SharedDirs: []string{"components", "layouts", "base"},
})

Templates in shared directories can be included from any feature template:

{{template "components/button" .}}
{{template "base/modal" .}}

This allows feature pages (e.g., features/dashboard/index) to remain isolated while sharing common components without naming conflicts.

Content Negotiation

// Returns HTML or JSON based on Accept header
render.Auto(c, http.StatusOK, "dashboard", data)

Index

Constants

View Source
const (
	ContentTypeHTML = "text/html; charset=utf-8"
	ContentTypeJSON = "application/json; charset=utf-8"
	ContentTypeXML  = "application/xml; charset=utf-8"
)

Content types for response headers.

View Source
const ContextKey = "render.engine"

ContextKey is the key used to store the Engine in the rig context.

Variables

This section is empty.

Functions

func Auto

func Auto(c *rig.Context, status int, templateName string, data any) error

Auto performs content negotiation based on the Accept header. It renders HTML (using the template) for browsers, or JSON for API clients. If a template name is empty, only JSON/XML responses are supported.

func AutoDirect

func AutoDirect(c *rig.Context, engine *Engine, status int, templateName string, data any) error

AutoDirect performs content negotiation using a specific engine.

func HTML

func HTML(c *rig.Context, status int, name string, data any) error

HTML renders a template and writes it as an HTML response. It retrieves the engine from the context (set by Middleware).

func HTMLDirect

func HTMLDirect(c *rig.Context, engine *Engine, status int, name string, data any) error

HTMLDirect renders a template using the provided engine directly. This is useful when you don't want to use middleware.

func HTMLSafe

func HTMLSafe(c *rig.Context, status int, name string, data any, errorTemplate string) error

HTMLSafe renders a template with automatic error page fallback. If the primary template fails to render, it attempts to render an error template (e.g., "errors/500" or "500") with the error details.

This is useful in production to show pretty error pages instead of returning raw error messages to users.

Example:

r.GET("/page", func(c *rig.Context) error {
    return render.HTMLSafe(c, http.StatusOK, "page", data, "errors/500")
})

The error template receives: {"Error": "error message", "StatusCode": 500}

func JSON

func JSON(c *rig.Context, status int, data any) error

JSON renders data as a JSON response.

func Partial

func Partial(c *rig.Context, status int, name string, data any) error

Partial renders a partial template (without layout) and writes it as an HTML response. This is commonly used for HTMX requests, dynamic widgets, or AJAX updates where you only need a fragment of HTML, not the full page shell.

It retrieves the engine from the context (set by Middleware).

func PartialDirect

func PartialDirect(c *rig.Context, engine *Engine, status int, name string, data any) error

PartialDirect renders a partial template using the provided engine directly. This is useful when you don't want to use middleware.

func XML

func XML(c *rig.Context, status int, data any) error

XML renders data as an XML response.

Types

type Config

type Config struct {
	// FileSystem allows loading templates from an embedded filesystem (embed.FS).
	// If nil, templates are loaded from the OS filesystem using Directory.
	// When set, Directory specifies the subdirectory within the FileSystem.
	//
	// Example with embed.FS:
	//   //go:embed templates/*
	//   var templateFS embed.FS
	//
	//   engine := render.New(render.Config{
	//       FileSystem: templateFS,
	//       Directory:  "templates",
	//   })
	FileSystem fs.FS

	// Directory is the root directory containing template files.
	// When FileSystem is nil, this is a path on the OS filesystem.
	// When FileSystem is set, this is a path within that filesystem.
	// Default: "templates".
	Directory string

	// Extensions is the list of file extensions to consider as templates.
	// Default: []string{".html", ".tmpl"}.
	Extensions []string

	// SharedDirs is a list of directories (relative to Directory) containing
	// templates that should be available globally to all other templates.
	//
	// Templates in these directories are treated as partials, meaning they
	// are loaded into the shared namespace and can be included from any template.
	// This enables component-based architecture without requiring underscore prefixes.
	//
	// Example:
	//   SharedDirs: []string{"components", "layouts", "base"}
	//
	// With this config, templates in "components/button.html" can be included
	// from any feature template using {{template "components/button" .}}
	//
	// This works alongside the underscore convention - files starting with "_"
	// are still treated as partials regardless of their directory.
	SharedDirs []string

	// Layout is the name of the base layout template (without extension).
	// If set, all templates will be rendered within this layout.
	// The layout should contain {{.Content}} to include page content.
	// Data passed to the template is available via {{.Data}}.
	// Default: "" (no layout).
	Layout string

	// DevMode enables hot reloading of templates on each request.
	// This is useful during development but should be disabled in production.
	// Default: false.
	DevMode bool

	// Funcs is a map of custom template functions.
	// These are available in all templates.
	Funcs template.FuncMap

	// Delims sets custom action delimiters for templates.
	// Useful when integrating with frontend frameworks like Vue.js, Angular,
	// or Alpine.js that also use {{ }} syntax.
	//
	// Example: []string{"[[", "]]"} changes Go templates to use [[ .Title ]]
	// Default: []string{"{{", "}}"} (standard Go template delimiters).
	Delims []string

	// Minify removes unnecessary whitespace from HTML output.
	// This can reduce bandwidth and improve page load times in production.
	// Default: false.
	Minify bool
}

Config defines the configuration for the template engine.

type Engine

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

Engine is the template rendering engine.

func GetEngine

func GetEngine(c *rig.Context) *Engine

GetEngine retrieves the render engine from the context. Returns nil if not found.

func New

func New(config Config) *Engine

New creates a new template engine with the given configuration.

func (*Engine) AddFunc

func (e *Engine) AddFunc(name string, fn any) *Engine

AddFunc adds a custom template function. This method is thread-safe and can be called concurrently, but should typically be called before Load() or Middleware() for best results.

func (*Engine) AddFuncs

func (e *Engine) AddFuncs(funcs template.FuncMap) *Engine

AddFuncs adds multiple custom template functions. This method is thread-safe and can be called concurrently, but should typically be called before Load() or Middleware() for best results.

func (*Engine) Load

func (e *Engine) Load() error

Load loads all templates from the configured directory. This is called automatically by Middleware(), but can be called manually to pre-load templates at startup.

Templates are loaded into a shared set, allowing them to reference each other. Files starting with underscore (e.g., _sidebar.html) are treated as partials and are automatically available to all templates.

When Config.FileSystem is set (e.g., embed.FS), templates are loaded from that filesystem. Otherwise, templates are loaded from the OS filesystem.

func (*Engine) Middleware

func (e *Engine) Middleware() rig.MiddlewareFunc

Middleware returns a rig middleware that injects the engine into the context. It also loads templates on first request (and on each request in DevMode).

func (*Engine) PartialNames

func (e *Engine) PartialNames() []string

PartialNames returns a list of all loaded partial names. Partials are templates whose filename starts with underscore.

func (*Engine) Render

func (e *Engine) Render(name string, data any) (string, error)

Render renders a template by name with the given data.

func (*Engine) RenderPartial

func (e *Engine) RenderPartial(name string, data any) (string, error)

RenderPartial renders a partial template by name with the given data. Unlike Render, this looks up the template in the shared partials set and does not wrap the output in a layout.

Partial names are the template names as loaded (e.g., "_header" or "partials/nav"). Use PartialNames() to see all available partials.

func (*Engine) TemplateNames

func (e *Engine) TemplateNames() []string

TemplateNames returns a list of all loaded template names. This is useful for debugging.

Jump to

Keyboard shortcuts

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