What is HTML/template in Golang?
HTML/template is a Golang (Go) package that implements data-driven templates for generating HTML outputs that are safe against code injection.
A key benefit of using HTML/template is that it produces safe, escaped HTML output using contextual auto-escaping. Therefore, whenever the output is HTML, the HTML/template package should always be used instead of text/template.
Escaping HTML output is important when preventing XSS attacks.
Syntax
HTML Syntax
HTML/template provides a rich set of control structures to render your HTML:
{{.}}: Renders the root element{{.Title}}: Renders the “Title”-field in a nested element{{if .Done}} {{else}} {{end}}: Defines an if-Statement{{range .Items}} {{.}} {{end}}: Loops over all “Items” and renders each using {{.}}{{block "myBlock" .}} {{end}}: Defines a block with the name “myBlock”{{/* a comment */}}: Defines a comment
Functions
Common HTML/template package functions:
func New(name string) *Template: Returns a newly allocated template with given namefunc (t *Template) Parse(text string) (*Template, error): Parses the given string as HTML template body fortfunc ParseFiles(filenames ...string) (*Template, error): Parses HTML from file and returns a new templatefunc (t *Template) Execute(wr io.Writer, data interface{}) error: Applies a parsed template to the specified data object by writingwr, the output to the passed io.Writer.
Example
Let’s create and output a simple ToDo list in HTML:
We define two structs: ToDo and PageData to store our ToDo list items data. We then create and parse the defined HTML template, tmpl. Finally, we render our HTML by passing the data and the parsed HTML template to the Execute() method.
package mainimport ("html/template""log""os")type Todo struct {Title stringDone bool}type PageData struct {PageTitle stringTodos []Todo}func main() {// An HTML templateconst tmpl = `<h1>{{.PageTitle}}</h1><ul>{{range .Todos}}{{if .Done}}<li>{{.Title}} ✔</li>{{else}}<li>{{.Title}}</li>{{end}}{{end}}</ul>`// Make and parse the HTML templatet, err := template.New("webpage").Parse(tmpl)if err != nil {log.Fatal(err)}// Initialze a struct storing page data and todo datadata := PageData {PageTitle: "My TODO list",Todos: []Todo{{Title: "Task 1", Done: false},{Title: "Task 2", Done: true},{Title: "Task 3", Done: true},},}// Render the data and output using standard outputt.Execute(os.Stdout, data)}
Free Resources