Golang html/template.HTML type examples

package html/template

HTML encapsulates a known safe HTML document fragment. It should not be used for HTML from a third-party, or HTML with unclosed tags or comments. The outputs of a sound HTML sanitizer and a template escaped by this package are fine for use with HTML.

Golang html/template.HTML type usage examples

Example 1:

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

Example 2:

 type info struct {
 Title string
 IE template.HTML
 }

 var ie template.HTML = `
 <!--[if lt IE 9]>
 <script src="js/html5shiv.min.js"></script>
 <script src="js/respond.min.js"></script>
 <![endif]-->`


 func rootHandler(w http.ResponseWriter, r *http.Request) {
  if r.URL.Path != "/" {
 http.NotFound(w, r)
 return
  }
  title := "Home"
  templates.ExecuteTemplate(w, "header.html", &info{title, ie})
  templates.ExecuteTemplate(w, "index.html", nil)
  templates.ExecuteTemplate(w, "footer.html", title)
 }

References :

https://github.com/aclissold/andrewclissold.appspot.com/blob/master/app.go

https://github.com/beego/bee/blob/master/bee.go

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

Advertisement