templatecheck

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Dec 8, 2020 License: MIT Imports: 7 Imported by: 3

README

templatecheck

Checking Go templates for validity.

Documentation

Overview

Package templatecheck checks Go templates for problems. It can detect many errors that are normally caught only during execution. By using templatecheck just after parsing, a program can find errors early in its lifetime, and along template execution paths that might only rarely be reached.

To use templatecheck on a template, that template must be invoked with the same Go type each time. Passing that type to templatecheck gives it enough information to verify that all the field references in the template are valid. templatecheck can also verify that functions are called with the right number of types of arguments, that the argument to a range statement can actually be ranged over, and a few other things.

Consider a web server that parses a template for its home page:

import "html/template"

var tmpl = template.Must(template.New("").ParseFiles("index.tmpl"))

func main() {
    ...
}

type homePage struct { ... }

func handler(w http.ResponseWriter, r *http.Request) {
    var buf bytes.Buffer
    if err := tmpl.Execute(&buf, homePage{...}); err != nil {
        http.Error(w, ...)
        return
    }
    _, err := w.Write(buf.Bytes())
    ...
}

Use templatecheck to catch errors at startup, instead of during serving:

func init() {
    if err := templatecheck.CheckHTML(tmpl, homePage{}); err != nil {
        log.Fatal(err)
    }
}

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CheckHTML

func CheckHTML(t *htmpl.Template, typeValue interface{}, funcMaps ...map[string]interface{}) error

CheckHTML checks an html/template for problems. See CheckText for details.

func CheckSafe

func CheckSafe(t *stmpl.Template, typeValue interface{}, funcMaps ...map[string]interface{}) error

CheckSafe checks a github.com/google/safehtml/template for problems. See CheckText for details.

func CheckText

func CheckText(t *ttmpl.Template, typeValue interface{}, funcMaps ...map[string]interface{}) error

CheckText checks a text/template for problems. The second argument is the type of dot passed to template.Execute. The remaining arguments are the FuncMaps passed to Template.Funcs (due to a limitation in the template package, templatecheck cannot retrieve these from the template.)

Types

This section is empty.