Part 003 Using A Map Of Interface With A Go Template

You can use templates with a map of interface. This is where reading in a JSON file and then mixing it with a template will really shine.

An example (ex3.go):

package main

// (C) Philip Schlump, 2013.
// MIT Licensed, see LICENSE.txt

import (
	"os"
	"text/template"
)

const templ = `
My name is: {{.Name}}.
My age is: {{.Age}}.

`

func main() {
	person := make(map[string]interface{}, 1)
	person["Name"] = "Philip J. Schlump"
	person["Age"] = 8 // Like I am really going to put in my age!

	t := template.New("simple-template")
	t, err := t.Parse(templ)
	if err != nil {
		panic(err)
		os.Exit(1)
	}

	err = t.ExecuteTemplate(os.Stdout, "simple-template", person)
	if err != nil {
		panic(err)
		os.Exit(1)
	}
}


To run this you can

$ go run ex3.go


To compile it and run it

$ go build ex3.go
$ ./ex3

The output is (ex3.out):

My name is: Philip J. Schlump.
My age is: 8.



Code tested on: Ubuntu 12.04, Mac 10.8, Windows 7 in go 1.1.2


•       •       •       •       •       •

Summary: # of Words: 122
Author: Philip J. Schlump
Published On: 2013-10-23

Download code from this articles in .tar.gz for Mac/Linux/Unix or .zip with CR/LF for Windows format.

 

Before You Go....

Have you read "Unintend Consinsequences"?

"I laughed so hard it hurt..."
    Rod Brown

"Incredibly funny! Incredibly true!"
    Tad Stevens