Golang html/template.Must and New functions examples

package html/template

New allocates a new HTML template with the given name.

Must is a helper that wraps a call to a function returning (*Template, error) and panics if the error is non-nil. It is intended for use in variable initializations such as

 var t = template.Must(template.New("name").Parse("html"))

Golang html/template.Must and New functions usage examples

Example 1:

 var TimeNowForm = template.Must(template.New("").ParseFiles("time.html"))

Example 2:

 func tmpl(w io.Writer, text string, data interface{}) {
  t := template.New("top")
  t.Funcs(template.FuncMap{"trim": strings.TrimSpace})
  template.Must(t.Parse(text))
  if err := t.Execute(w, data); err != nil {
 panic(err)
  }
 }

References :

https://github.com/beego/i18n/blob/master/beei18n/beei18n.go

http://golang.org/pkg/html/template/#Must

http://golang.org/pkg/html/template/#New

Advertisement