Created
October 3, 2017 18:02
-
-
Save meling/6373bb6a7f6717c3cd9a2b10e483961e to your computer and use it in GitHub Desktop.
Defining template can't access outer context
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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