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 (

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

func NewContactForm(Subject, Name, Email, Message string) *ContactForm {
	return &ContactForm{

var tpl = template.Must(template.New("new_message").Parse(`
<p>You have received a message from {{.Name}}</p>
{{range $key,$value :=.Data}}
<p>With Regards.</p>

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 {
	fmt.Println("Here is the out put")
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