Skip to content

Instantly share code, notes, and snippets.

@meling
Created October 3, 2017 18:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save meling/6373bb6a7f6717c3cd9a2b10e483961e to your computer and use it in GitHub Desktop.
Save meling/6373bb6a7f6717c3cd9a2b10e483961e to your computer and use it in GitHub Desktop.
Defining template can't access outer context
package main
import "text/template"
import "os"
type address struct {
House string
Street string
PostCode string
Country string
}
type person struct {
FirstName string
FamilyName string
Address address
PhoneNumbers []string
}
func main() {
source :=
`{{ "Who's this guy and where does he live" }}
{{define "phony"}}
{{.}} and his family name is {{$.FamilyName}}
{{- end -}}
{{.FirstName}} {{.FamilyName}}
{{with .Address -}}
The {{ .Country }} is where {{$.FirstName}} lives. {{/* . refers to Address instance */}}
{{end}}
His phone numbers are:
{{- range .PhoneNumbers -}}
{{template "phony" .}}
{{- end}}
`
p := person{FirstName: "Markus", FamilyName: "Ryan", Address: address{Country: "UK"}, PhoneNumbers: []string{"123", "456", "789"}}
tmpl := template.Must(template.New("table").Parse(source))
err := tmpl.Execute(os.Stdout, p)
if err != nil {
panic(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment