You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
package templates
import (
"os""strings""text/template"
)
constsampleTemplate=` This template demonstrates printing a {{ .Variable | printf "%#v" }}. {{if .Condition}} If condition is set, we'll print this {{else}} Otherwise, we'll print this instead {{end}} Next we'll iterate over an array of strings: {{range $index, $item := .Items}} {{$index}}: {{$item}} {{end}} We can also easily import other functions like strings.Split then immediately used the array created as a result: {{ range $index, $item := split .Words ","}} {{$index}}: {{$item}} {{end}} Blocks are a way to embed templates into one another {{ block "block_example" .}} No Block defined! {{end}} {{/* This is a way to insert a multi-line comment */}}`constsecondTemplate=` {{ define "block_example" }} {{.OtherVariable}} {{end}}`// RunTemplate initializes a template and demonstrates a // variety of template helper functionsfuncRunTemplate() error {
data:=struct {
ConditionboolVariablestringItems []stringWordsstringOtherVariablestring
}{
Condition: true,
Variable: "variable",
Items: []string{"item1", "item2", "item3"},
Words:
"another_item1,another_item2,another_item3",
OtherVariable: "I'm defined in a second template!",
}
funcmap:= template.FuncMap{
"split": strings.Split,
}
// these can also be chainedt:=template.New("example")
t=t.Funcs(funcmap)
// We could use Must instead to panic on error// template.Must(t.Parse(sampleTemplate))t, err:=t.Parse(sampleTemplate)
iferr!=nil {
returnerr
}
// to demonstrate blocks we'll create another template// by cloning the first template, then parsing a secondt2, err:=t.Clone()
iferr!=nil {
returnerr
}
t2, err=t2.Parse(secondTemplate)
iferr!=nil {
returnerr
}
// write the template to stdout and populate it// with dataerr=t2.Execute(os.Stdout, &data)
iferr!=nil {
returnerr
}
returnnil
}
Working with template files
package templates
import (
"io/ioutil""os""path/filepath""text/template"
)
//CreateTemplate will create a template file that contains datafuncCreateTemplate(pathstring, datastring) error {
returnioutil.WriteFile(path, []byte(data),
os.FileMode(0755))
}
// InitTemplates sets up templates from a directoryfuncInitTemplates() error {
tempdir, err:=ioutil.TempDir("", "temp")
iferr!=nil {
returnerr
}
deferos.RemoveAll(tempdir)
err=CreateTemplate(filepath.Join(tempdir, "t1.tmpl"),
`Template 1! {{ .Var1 }} {{ block "template2" .}} {{end}} {{ block "template3" .}} {{end}} `)
iferr!=nil {
returnerr
}
err=CreateTemplate(filepath.Join(tempdir, "t2.tmpl"),
`{{ define "template2"}}Template 2! {{ .Var2 }}{{end}} `)
iferr!=nil {
returnerr
}
err=CreateTemplate(filepath.Join(tempdir, "t3.tmpl"),
`{{ define "template3"}}Template 3! {{ .Var3 }}{{end}} `)
iferr!=nil {
returnerr
}
pattern:=filepath.Join(tempdir, "*.tmpl")
// Parse glob will combine all the files that match // glob and combine them into a single templatetmpl, err:=template.ParseGlob(pattern)
iferr!=nil {
returnerr
}
// Execute can also work with a map instead// of a structtmpl.Execute(os.Stdout, map[string]string{
"Var1": "Var1!!",
"Var2": "Var2!!",
"Var3": "Var3!!",
})
returnnil
}
Working with html template
package templates
import (
"fmt""html/template""os"
)
// HTMLDifferences highlights some of the differences// between html/template and text/templatefuncHTMLDifferences() error {
t:=template.New("html")
t, err:=t.Parse("<h1>Hello! {{.Name}}</h1>n")
iferr!=nil {
returnerr
}
// html/template auto-escapes unsafe operations like // javascript injection this is contextually aware and // will behave differently// depending on where a variable is renderederr=t.Execute(os.Stdout, map[string]string{"Name": " <script>alert('Can you see me?')</script>"})
iferr!=nil {
returnerr
}
// you can also manually call the escapersfmt.Println(template.JSEscaper(`example <[email protected]>`))
fmt.Println(template.HTMLEscaper(`example <[email protected]>`))
fmt.Println(template.URLQueryEscaper(`example <[email protected]>`))
returnnil
}