zgo.at/ztpl Index | Files | Directories

package ztpl

import "zgo.at/ztpl"

Package ztpl implements the loading and reloading of templates.

Index

Package Files

ztpl.go

func Execute

func Execute(w io.Writer, name string, data interface{}) error

Execute a named template.

func ExecuteBytes

func ExecuteBytes(name string, data interface{}) ([]byte, error)

ExecuteBytes a named template and return the data as a byte slice.

func ExecuteString

func ExecuteString(name string, data interface{}) (string, error)

ExecuteString a named template and return the data as a string.

func HasTemplate

func HasTemplate(name string) bool

HasTemplate reports if this template is loaded.

func Init

func Init(files fs.FS) error

Init sets up the templates.

This assumes that HTML templates have the .gohtml extension, and that text templates have the .gotxt extension.

func IsLoaded

func IsLoaded() bool

IsLoaded reports if templates have been loaded.

func List

func List() []string

List all template names.

func Reload

func Reload(path string) error

Reload the templates from the filesystem.

func TestTemplateExecution

func TestTemplateExecution(m interface{ Run() int }, ignore ...string) int

TestTemplateExecution tests if all templates loaded through ztpl are executed.

Go templates are dynamically typed and not counted in code coverage tools; this is a simple way to ensure all templates are executed at least once.

Typical usage would be:

func TestMain(m *testing.M) {
    os.Exit(ztpl.TestTemplateExecution(m, "ignore_this.gohtml"))
}

func TestTemplateExecution(m *testing.M, ignore ...string) int {

func Trace

func Trace(on bool) internal.Trace

Trace enables tracking of all template executions. When this is disabled the stored list is emptied and the previous value returned.

This is mostly useful for tracking which templates are run from tests, e.g.:

func TestMain(m *testing.M) {
    ztpl.Trace(true)
    c := m.Run()

    ran := ztpl.Trace(false)
    for _, t := range ztpl.List() {
        if _, ok := ran[t]; !ok {
            fmt.Println("didn't execute template", t)
        }
    }
    os.Exit(c)
}

Also see TestTemplateExecution(), which wraps this for convenient use.

Directories

PathSynopsis
internal
parsePackage parse builds parse trees for templates as defined by text/template and html/template.
tplfunc
Version
v0.0.0-20211128061406-6ff34b1256c4 (latest)
Published
Nov 28, 2021
Platform
linux/amd64
Imports
13 packages (graph)
Last checked
1 month ago

Tools for package owners.