Part 007 Calling Go Functions From A Go Template

One of the powerful things in the Go template processor is the ability to call functions inside the code. This is one of the things that confused me when I first used it. Hopefully this example will help alleviate the confusion.

An example (ex7.go):

package main

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

// Example of calling a function from a template

import (
	"encoding/json"
	"fmt"
	"html/template"
	"io/ioutil"
	"os"
)

// -----------------------------------------------------------------------------
// This will be used to extend the template language
// -----------------------------------------------------------------------------
func bob(in string) string {
	// Silly function just concatenates some strings
	return "BOB GOT CALLED! Input [" + in + "]"
}

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

func readInJson(path string) map[string]interface{} {
	var jsonData map[string]interface{}
	file, err := ioutil.ReadFile(path)
	if err != nil {
		return jsonData
	}
	json.Unmarshal(file, &jsonData)
	return jsonData
}

func main() {

	if len(os.Args) != 3 {
		fmt.Printf("Usage: ex7 TemplateFileName Data.JSON\n")
		os.Exit(1)
	}

	// Look for *bob* in the template (2 locations)
	var tmpl_fn string = os.Args[1]
	var data_fn string = os.Args[2]

	tmpl := readInFile(tmpl_fn)
	person := readInJson(data_fn)

	funcMap := template.FuncMap{
		"bob": bob,
	}

	// Where we tell the template processor about "bob"
	t := template.New("file-template").Funcs(funcMap)
	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)
	}
}


In this example the function bob is called from inside the template.

To run this you can

$ go run ex7.go ex7.tmpl ex7.json


To compile it and run it

$ go build ex7.go
$ ./ex7 ex7.tmpl ex7.json

The output you should expect from running it is (ex7.out):


My name is: example name.

BOB GOT CALLED! Input [Call ]

BOB GOT CALLED! Input [example name]



Next: An example of function calls with useful functions!

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


•       •       •       •       •       •

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