Golang html/template.FuncMap type examples

package html/template

FuncMap is the type of the map defining the mapping from names to functions. Each function must have either a single return value, or two return values of which the second has type error. In that case, if the second (error) argument evaluates to non-nil during execution, execution terminates and Execute returns that error. FuncMap has the same base type as FuncMap in "text/template", copied here so clients need not import "text/template".

Golang html/template.FuncMap type usage examples

Example 1:

 func init() {
  ...
 beegoTplFuncMap = make(template.FuncMap)
 ...
  beegoTplFuncMap["dateformat"] = DateFormat
  beegoTplFuncMap["date"] = Date
  beegoTplFuncMap["compare"] = Compare
  beegoTplFuncMap["substr"] = Substr
  beegoTplFuncMap["html2str"] = Html2str
  beegoTplFuncMap["str2html"] = Str2html
  beegoTplFuncMap["htmlquote"] = Htmlquote
  beegoTplFuncMap["htmlunquote"] = Htmlunquote
  beegoTplFuncMap["renderform"] = RenderForm
  beegoTplFuncMap["assets_js"] = AssetsJs
  beegoTplFuncMap["assets_css"] = AssetsCss
  beegoTplFuncMap["config"] = Config
  // go1.2 added template funcs
  // Comparisons
  beegoTplFuncMap["eq"] = eq // ==
  beegoTplFuncMap["ge"] = ge // >=
  beegoTplFuncMap["gt"] = gt // >
  beegoTplFuncMap["le"] = le // <=
  beegoTplFuncMap["lt"] = lt // <
  beegoTplFuncMap["ne"] = ne // !=
  beegoTplFuncMap["urlfor"] = UrlFor // !=
 }

Example 2:

 // LoadTemplates pre-loads templates from the configured template directory
 func (h *HTTP) LoadTemplates(name string) (t *template.Template, err error) {
  t = template.New("t")
  t.Funcs(template.FuncMap{
 "add": add,
 "sizeof":  readableSize,
 "version": version,
  })
  t, err = t.ParseFiles(
 fmt.Sprintf("%s/base.html", GetConfig().Templates),
 fmt.Sprintf("%s/%s.html", GetConfig().Templates, name))
  if err != nil {
 panic(err)
  }
  return t, err
 }

References :

https://github.com/astaxie/beego/blob/master/template.go

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

https://github.com/etix/mirrorbits/blob/master/http.go

Advertisement