view

package
v14.0.0 Latest Latest
Warning

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

Go to latest
Published: Nov 12, 2026 License: BSD-3-Clause, BSD-3-Clause Imports: 6 Imported by: 0

README

Views

The view middleware renders templates. It works with any engine that implements the Engine interface, switches layouts per route or per request, binds data to a template from a handler or from middleware, and lets you register your own template functions.

Key Features

  • Template Engine Integration: Supports multiple template engines by implementing the Engine interface.
  • Layout Management: Define and switch layouts dynamically for consistent page structure.
  • Data Binding: Pass data to your templates via middleware or within handlers.
  • Custom Template Functions: Extend your templates with custom functions for reusable logic.
  • Middleware Architecture: Set the engine, the layout and the view data from middleware, so handlers stay short.

Installation

First, make sure you have the Iris framework installed:

go get github.com/kataras/iris/v14@latest

Look at https://github.com/iris-contrib/views for more template engines.

go get github.com/iris-contrib/views@latest

Getting Started

Defining the Engine

The middleware is built around the Engine interface, which any template engine must implement to be compatible:

type Engine interface {
    ExecuteTemplate(w io.Writer, templateName string, layoutName string, data any) error
}

You can use any template engine that satisfies this interface. For example, using the blocks template engine:

go get github.com/kataras/blocks@latest
import (
    "github.com/kataras/iris/v14"
    "github.com/kataras/iris/v14/middleware/view"
    "github.com/kataras/iris/v14/rest/errors"

    "github.com/kataras/blocks"
)

func main() {
    app := iris.New()
    templates := blocks.New("./views")
    if err := templates.Load(); err != nil {
        panic(err)
    }

    // Register the view middleware at the router level
    app.UseRouter(view.Handler(templates))

    // Define your routes
    app.Get("/", indexHandler)

    app.Listen(":8080")
}
Rendering Templates

In your handler functions, you can render templates using the view.Render function:

func Render(ctx iris.Context, templateName, layoutName string, data any) error
func indexHandler(ctx iris.Context) {
    data := iris.Map{
        "Title": "Home Page",
    }

    if err := view.Render(ctx, "index", "main", data); err != nil {
        errors.Internal.LogErr(ctx, err)
        return
    }
}

errors is the rest/errors package imported above. A template error names files, lines and data fields, so errors.Internal.LogErr writes it to the server log and the client receives a generic 500. Do not send err.Error() to the browser.

Alternatively, you can use the Template struct for more structured rendering:

app.Get("/about", view.WithTemplate(&view.Template{
    Name:   "about",
    Layout: "main",
    Data: iris.Map{
        "Title": "About Us",
    },
}))
Managing Layouts

Layouts provide a way to define a common structure for your views, such as headers and footers.

Passing layout directly in the Render function:

view.Render(ctx, "index", "layout_name", data)

To set a layout for a specific request through the Layout function (useful when you want to change layouts dynamically):

view.Layout(ctx, "layout_name")

To set a default layout for all requests using middleware:

app.Use(view.WithLayout("default_layout"))
Passing Data to Templates

You can pass data to your templates directly in your handlers or through middleware.

Passing data directly:

data := iris.Map{
    "Title":   "Page Title",
    "Content": "Welcome to our site!",
}
view.Render(ctx, "index", "", data)

Passing data within handlers dynamically:

// Set template data
view.Data(ctx, data)

// Add key-value pair
view.KeyValue(ctx, "key", value)

Using middleware to set data:

app.Use(view.WithData(iris.Map{
    "AppName": "My Iris App",
}))

The map given to view.WithData is stored on every request, so all requests share it. view.KeyValue does not write into it. The first call of a request copies the map and adds the key to the copy, and view.GetData(ctx) returns the result. A key added for one request is never seen by another.

Adding Custom Template Functions

A template function belongs to the engine, so register it on the engine before Load. With blocks:

templates := blocks.New("./views").Funcs(template.FuncMap{
    "ToUpper": strings.ToUpper,
    "FormatDate": func(t time.Time) string {
        return t.Format("Jan 2, 2006")
    },
})
if err := templates.Load(); err != nil {
    panic(err)
}

app.UseRouter(view.Handler(templates))

A template then calls {{ ToUpper .Title }}. The order matters. html/template resolves function names while it parses, so Load fails with function "ToUpper" not defined when the function is not there yet.

The middleware can register functions as well, on an engine that implements the EngineFuncer interface:

type EngineFuncer interface {
    AddFunc(funcName string, funcBody any)
}
view.AddFunc(ctx, "ToUpper", strings.ToUpper)
app.Use(view.WithFuncMap(template.FuncMap{
    "ToUpper": strings.ToUpper,
}))

Both call AddFunc on the engine that the request holds, and they do it when a request arrives. Two things follow from that:

  • The function is not per-request state. Every request and every route that uses the engine can call it from then on. Never pass a function that closes over ctx, because it stays on the engine after the request has ended.
  • It is too late for an engine that was loaded at startup, as blocks is in every example here. It is in time only for an engine that has not loaded its templates yet. The engines of iris-contrib/views load on the first render when you did not call Load yourself.

A function that depends on the request goes into the view data, like any other value:

view.KeyValue(ctx, "Greet", func(name string) string {
    return ctx.Query().Get("lang") + ": " + name
})

The template calls it with {{ call .Greet .Name }}.

Advanced Topics

Template Engines

The middleware works with any template engine that implements the Engine interface. That is the Strategy Pattern: swapping engines does not touch your application code.

Error Handling

view.Render returns an error when the template or the layout does not exist, when the engine fails to execute it, and when no engine is registered for the route (view.ErrNoEngine). Log it and answer with a generic 500:

if err := view.Render(ctx, "index", "main", data); err != nil {
    errors.Internal.LogErr(ctx, err)
    return
}

view.WithTemplate needs no such branch. It stops the request and keeps the error private by itself.

Load Errors

The framework does not load templates for you, so a broken template cannot stop app.Listen on its own. Load returns the error to your code and you choose what it means. The examples here panic, which is right when a release with a broken page must not start. To keep the rest of the application serving, log it instead:

templates := blocks.New("./views")
if err := templates.Load(); err != nil {
    app.Logger().Errorf("views: %v", err)
}

app.UseRouter(view.Handler(templates))

Every other route answers as usual. A route that renders gets the error back from view.Render and answers 500 through the branch above. Call templates.Load() again once the file is fixed and the same running application renders it, with no restart.

Example Application

Below is a simple example demonstrating how to set up the view middleware with routes and templates:

package main

import (
    "github.com/kataras/iris/v14"
    "github.com/kataras/iris/v14/middleware/view"
    "github.com/kataras/iris/v14/rest/errors"

    "github.com/kataras/blocks"
)

func main() {
    app := iris.New()
    templates := blocks.New("./views")
    if err := templates.Load(); err != nil {
        panic(err)
    }

    app.UseRouter(view.Handler(templates))
    app.Use(view.WithLayout("main")) // Set default layout.

    app.Get("/", indexHandler)
    app.Get("/500", errorHandler)

    app.Listen(":8080")
}

func indexHandler(ctx iris.Context) {
    data := iris.Map{
        "Title": "Welcome",
    }

    if err := view.Render(ctx, "index", "", data); err != nil {
        errors.Internal.LogErr(ctx, err)
        return
    }
}

func errorHandler(ctx iris.Context) {
    ctx.StatusCode(iris.StatusInternalServerError)
    data := iris.Map{
        "Code":    iris.StatusInternalServerError,
        "Message": "Something went wrong!",
    }

    if err := view.Render(ctx, "500", "error", data); err != nil {
        errors.Internal.LogErr(ctx, err)
        return
    }
}

Best Practices

  • Modular Design: Keep your template logic modular by using layouts and partials.
  • Data Separation: Separate your data preparation from your rendering logic.
  • Error Handling: Always check for errors when rendering templates.
  • Custom Functions: Extend your templates with custom functions for reusable logic.

References

Documentation

Overview

Package view registers a template engine so that Render, WithTemplate and Context.Render can render its templates. The engines live outside the framework: HTML, Django, Handlebars, Jet, Pug and Ace are in github.com/iris-contrib/views and Blocks is github.com/kataras/blocks. Any type that implements Engine can be registered.

Its entry point is Handler(engine), which returns a Handler that binds the engine to the requests that follow it. The engine itself is the single input, so it is a plain argument and there is no Options struct.

Index

Constants

This section is empty.

Variables

View Source
var ErrNoEngine = errors.New("view engine is not available in the current context")

ErrNoEngine reports whether a view engine is not available in the current context. It's used when trying to render a view without a view engine.

Functions

func AddFunc

func AddFunc(ctx *context.Context, funcName string, fn any) bool

AddFunc adds a template function to the view engine that the request holds. It reports whether that engine takes functions, which means that it implements EngineFuncer.

The function is registered on the engine, so it is not per-request state:

  • Every request and every route that uses the same engine can call it from then on.
  • Do not pass a function that closes over ctx. It stays on the engine after the request has ended, while the Context it captured goes back to the pool and serves other requests. A value that belongs to one request goes into the view data (see Data and KeyValue), a function included: a template calls it with {{ call .Name arguments }}.
  • When the function becomes callable depends on the engine. One that resolves function names while it parses, as html/template does, needs the function before it loads its templates, and an engine that is loaded at startup has done that before the first request arrives. For such an engine call its own AddFunc or Funcs method before Load.

Example:

rv := router.NewRoutePathReverser(app.RouterBuilder.Routes())
view.AddFunc(ctx, "urlpath", rv.Path)

func Data

func Data(ctx *context.Context, data any)

Data sets the view data to the context, by overriding any previous data.

func Ext

func Ext(ctx *context.Context) string

Ext returns the final file extension (including the dot) which the view engine is responsible to render. It returns an empty string if the engine is not available in the current context.

func GetData

func GetData(ctx *context.Context) any

GetData returns the view data from the context.

func Handler

func Handler(engine Engine) context.Handler

Handler returns a context.Handler that stores the view engine to the context, by overriding any previous ones for the handler (chain).

func KeyValue

func KeyValue(ctx *context.Context, key string, value any) error

KeyValue adds a key-value pair to the view data of the current request. The view data is created as a Map if it doesn't exist. If the view data is not a Map, it returns an error.

KeyValue never writes into a map that was given to Data or WithData, because WithData stores the same map on every request. The first call of a request copies such a map and writes to the copy, and the calls that follow reuse it. The map of the caller stays as it was, so read the result with GetData. The copy is shallow: a value that is itself a map or a slice is still shared.

func Layout

func Layout(ctx *context.Context, layout string)

Layout sets the view layout to the context, by overriding any previous layout.

func Render

func Render(ctx *context.Context, templateName, layoutName string, data any) error

Render renders a template by its filename with an optional layout and data. It writes the response headers and body. It returns an error if the engine is not available in the current context. If the given "layoutName" is empty then it tries to get the layout from the context's view layout (see `Layout` function). If the given "data" is nil then it tries to get the data from the context's view data (see `Data` and `KeyValue` functions).

func WithData

func WithData(data any) context.Handler

WithData returns a context.Handler that stores the view data to the context, by overriding any previous ones for the handler (chain).

Every request that passes through the handler gets the same value, so do not change it once the server runs. KeyValue does not: it copies a map before the first write of a request.

func WithFuncMap

func WithFuncMap(funcMap template.FuncMap) context.Handler

WithFuncMap returns a context.Handler that adds the given template.FuncMap to the view engine of the request, by calling AddFunc for each entry.

The functions are registered on the engine and not on the request, so read AddFunc before you use it. The handler adds the same functions again on every request, which only helps an engine that has not loaded its templates yet. To register functions once, call the engine's own method before its Load.

func WithLayout

func WithLayout(layout string) context.Handler

WithLayout returns a context.Handler that stores the view layout to the context, by overriding any previous ones for the handler (chain).

func WithTemplate

func WithTemplate(t *Template) context.Handler

WithTemplate returns a Handler that renders the given template.

Types

type Engine

type Engine interface {
	// ExecuteTemplate should execute a template by its filename with an optional layout and data.
	ExecuteTemplate(w io.Writer, templateName string, layoutName string, data any) error
}

Engine is the interface which all view engines should be implemented in order to be registered inside iris.

type EngineExtenser

type EngineExtenser interface {
	// Ext should return the final file extension (including the dot)
	// which this view engine is responsible to render.
	Ext() string
}

EngineExtenser is the interface which supports the retrieval of the template files extension.

type EngineFuncer

type EngineFuncer interface {
	// AddFunc should adds a function to the template's function map.
	AddFunc(funcName string, funcBody any)
}

EngineFuncer is the interface which supports the registration of custom template functions.

type ErrTemplateNotFound

type ErrTemplateNotFound struct {
	Name     string
	IsLayout bool
	Data     any
}

ErrTemplateNotFound it's an error. It reports whether a template was not found in the parsed templates tree.

func (ErrTemplateNotFound) Error

func (e ErrTemplateNotFound) Error() string

Error completes the `error` interface.

type Template

type Template struct {
	Code   int    `json:"code" yaml:"Code"`
	Layout string `json:"layout" yaml:"Layout"`
	Name   string `json:"name" yaml:"Name"`
	Data   any    `json:"data" yaml:"Data"`

	// DataFunc can be used in order to return some `Data` based on the iris Context,
	// from outside the context. E.g. when declaring the View outside of the handler scope.
	//
	// When DataFunc is not nil its result is rendered and the Data field is
	// ignored. The result belongs to the request: Render does not store it in
	// the Template, because WithTemplate gives the same Template to every
	// request of a route.
	DataFunc func(*context.Context) (any, error) `json:"-" yaml:"-"`
}

Template represents a view. It's used to render a view with a specific status code, layout and data. Usage:

ctx.Render(&Template{Name: "index.html", Layout: "layouts/main.html", Data: someData})

func (*Template) Render

func (t *Template) Render(ctx *context.Context) error

Render renders the template. It writes the response headers and body. It completes the `Renderer` interface.

Render does not change the Template, so one Template can render many requests at the same time.

Jump to

Keyboard shortcuts

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