Templating in golang

Golang has built in support for text and html templating. We use text/template and html/template packages respectively for text and html templates. Both packages are almost identical but for extra HTML encoding done by the html/template package.
Lets see a quick example
package main

import (
	"bytes"
	"fmt"
	"html/template"
)

type ContactForm struct {
	Subject, Name, Email, Message string
	Data                          map[string]string
}

func NewContactForm(Subject, Name, Email, Message string) *ContactForm {
	return &ContactForm{
		Subject,
		Name,
		Email,
		Message,
		map[string]string{},
	}
}

var tpl = template.Must(template.New("new_message").Parse(`
<html>
<head><title>{{.Subject}}</title>
</head>
<body>
<p>You have received a message from {{.Name}}</p>
<table>
<tr><td>Name</td><td>{{.Name}}</td></tr>
<tr><td>Email</td><td>{{.Email}}</td></tr>
{{range $key,$value :=.Data}}
<tr><td>{{$key}}</td><td>{{$value}}</td></tr>
{{end}}
<tr><td>Message</td><td>{{.Message}}</td></tr>
</table>
<p>With Regards.</p>
</body>
</html>
`))

func main() {
	//Build the data. We'll hard code the values here.
	form := NewContactForm("Hello", "Nirandas", "connect@nirandas.com", "A sample message body.")
	form.Data["department"] = "Sales"

	//execute the template
	var b bytes.Buffer // io.writer to hold the output
	err := tpl.Execute(&b, form)
	if err != nil {
		panic(err)
	}
	fmt.Println("Here is the out put")
	fmt.Println(b.String())
}
The template demonstrates simple variable replacement as well as using a loop. Read more at golang docs html/template
© 2018 Nirandas Thavorath. All Rights Reserved.
Last updated at Thursday July 20, 2017 09:21 PM