Part 014 Variables In Go Templates

Note: These functions are now included as a part of the standard set of functions in the Go templates. I have left this blog post up because it was critical to my understanding of just how extensible the Go template system is.

Go Templates give the you the ability to create a variable. At first I couldn't see a reason to ever create a variable. Then I used a loop in a template and needed to access some data from outside the loop. Oops! About 20 Google searches later and I had a reason to declare a variable.

An example (ex14.tmpl):

{{$top := .Top}}
{{range $i, $e := .AllLabelsData}}
	<li><a tabindex="-1" href="{{$top}}posts/{{$e.Url}}">{{$e.Title}}</a></li>

Line 1 declares the variable $top. It is used in the href= on line 3.

As soon as I had this figured out I knew that I had a way to pass data into a template. Let's try it. (ex14b.tmpl):

{{define "test"}}
	This is Test

{{$var = "bob"}}

{{template "test"}}

I ran it.

$ go run ex8.go ex14b.tmpl ex8.json

I was very disappointed when I found out that variables are not global scope. This is what I got for output (ex14b.out):

panic: template: file-template:4: undefined variable "$var"

goroutine 1 [running]:
	/home/pschlump/www/sketchground/pjs/99-static/res/2013-10-23-Simple-Go-Template-Usage/ex8.go:142 +0x25e

goroutine 3 [runnable]:
text/template/parse.lexRightDelim(0xc2000b5000, 0x5aebd8)
	/usr/local/go/src/pkg/text/template/parse/lex.go:258 +0xb6
	/usr/local/go/src/pkg/text/template/parse/lex.go:198 +0x3e
created by text/template/parse.lex
	/usr/local/go/src/pkg/text/template/parse/lex.go:191 +0x111
exit status 2

Oh, well…

Code tested on: Ubuntu 13.04, Mac 13.8, Windows 7 in go 1.1.2

•       •       •       •       •       •

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