Last active
August 29, 2015 14:18
-
-
Save stephenwithav/70e46bc42ae793092d9d to your computer and use it in GitHub Desktop.
example of using text/template
This file contains 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 ( | |
"os" | |
"text/template" | |
) | |
var peoplePage *template.Template | |
var peopleTemplate string = `{{range .}} | |
{{.FirstName}} {{.LastName}} is {{.Age}} years old. | |
In 10 years, {{.FirstName}} will be {{add .Age 10}}. | |
{{end}}` | |
func init() { | |
peoplePage = template.Must(template.New("peopleTemplate").Funcs(template.FuncMap{ | |
"add": add, | |
}).Parse(peopleTemplate)) | |
} | |
type Person struct { | |
FirstName string | |
LastName string | |
Age int | |
} | |
var people = []Person{ | |
{"John", "Smith", 22}, | |
{"Alice", "Smith", 25}, | |
{"Bob", "Baker", 24}, | |
} | |
func main() { | |
peoplePage.Execute(os.Stdout, people) | |
} | |
func add(a int, b int) int { | |
return a + b | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment