Part 009 Template Function With Multiple Arguments

The Go Template processor can call functions with multiple arguments. This was not apparent to me when I read the documentation. The example in the documentation shows calling string.Title. This is a function with a single string input and returns a string. In fact this example is why I have written the multi-part set of blog posts on Go Templates. I really had difficulty understating what I could and could not do with the templates.

An example (ex9.go):

package main

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

// Example of calling a function with a variable parameter list from a template

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

// -----------------------------------------------------------------------------
//
// Function: concat
//
// Description:  This is an example of how to concatenate strings using a
// function in Go called from a template.  This is not the most useful
// function.  However it is simple and shows how a function with a variable
// list of string parameters works.
//
// -----------------------------------------------------------------------------
func concat(args ...string) (s string) {
	s = ""
	for _, v := range args {
		s = s + v
	}
	return
}

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: ex9 TemplateFileName Data.JSON\n")
		os.Exit(1)
	}

	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{
		"concat": concat, // Simple multi parameter function
	}

	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 ex9.go ex9.tmpl ex9.json


To compile it and run it

$ go build ex9.go
$ ./ex9 ex9.tmpl ex9.json

The JSON input is (ex9.json):

{
	 "Data1": "[DATA 1]"
	,"Data2": "[DATA 2]"
	,"Data3": "[DATA 3]"
	,"not-relevant-data": "ignored"
}


The template input is (ex9.tmpl):


Demo of string concat.

constants {{concat "a" "b" "c"}}

from JSON file {{concat .Data1 .Data2 .Data3}}

Mixed JSON and constants {{concat .Data1 "!=" .Data2 "!=" .Data3}}





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


Demo of string concat.

constants abc

from JSON file [DATA 1][DATA 2][DATA 3]

Mixed JSON and constants [DATA 1]!=[DATA 2]!=[DATA 3]





The concatenate function takes a set of strings as arguments and returns a single string.

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


•       •       •       •       •       •

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