ztpl – zgo.at/ztpl Index | Files | Directories

package ztpl

import "zgo.at/ztpl"

Package ztpl implements the loading and reloading of templates.



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 Parse

func Parse(
	name, text string,
	mode parse.Mode,
	leftDelim, rightDelim string,
	funcs ...map[string]interface{},
) (map[string]*parse.Tree, error)

Parse a template and set the mode.

func PrintTree

func PrintTree(w io.Writer, node parse.Node)

PrintTree prints the tree to w.

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) {
    c := m.Run()

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

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

func Visit

func Visit(node parse.Node, f func(parse.Node, int) bool)

Visit every node and call f.

Traverse in the node if the return value of f is true.

Source Files

visit.go ztpl.go


v0.0.0-20240407165537-1af004e73b6e (latest)
Apr 7, 2024
14 packages
Last checked
3 days ago

Tools for package owners.