Part 004 Reading In The Go Template

It is simple to read in the template from a file. ioutil.ReadFile reads in the entire file to an array of byte. Then we convert the file to a string.

An example (ex4.go):

package main

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

// Read in Template then process it

import (
	"io/ioutil"
	"os"
	"text/template"
)

func readInFile(path string) string {
	file, err := ioutil.ReadFile(path)
	if err != nil {
		return ""
	}
	return string(file)
}

func main() {
	tmpl := readInFile("ex4.tmpl")

	person := make(map[string]interface{}, 1)
	person["Name"] = "Philip J. Schlump"

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

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


To run this you can

$ go run ex4.go


To compile it and run it

$ go build ex4.go
$ ./ex4

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


•       •       •       •       •       •

Summary: # of Words: 119
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