Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@juanpabloaj
Last active August 19, 2019 20:34
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 juanpabloaj/8034e90ee4035a3e6009ba0f6bb750d2 to your computer and use it in GitHub Desktop.
Save juanpabloaj/8034e90ee4035a3e6009ba0f6bb750d2 to your computer and use it in GitHub Desktop.
go template example
package main
import (
"os"
"text/template"
"time"
)
type Todo struct {
Name string
Description string
CreatedOn time.Time
}
type templateInput struct {
State map[string]interface{}
}
func localSum(a, b int) int {
return a + b
}
func localAddDays(d time.Time, days int) time.Time {
return d.AddDate(0, 0, days)
}
var funcMap = template.FuncMap{
"now": time.Now,
"sum": localSum,
"addDays": localAddDays,
}
// withAddDay addDays(now, 2)
func withAddDays() {
tmplInput := templateInput{
map[string]interface{}{
"days": 2,
},
}
tmpl := `{{now.Day}} until two days: {{ addDays now (index .State "days")}}`
t, err := template.New("withState").Funcs(funcMap).Parse(tmpl)
if err != nil {
panic(err)
}
err = t.Execute(os.Stdout, tmplInput)
if err != nil {
panic(err)
}
}
// withComposition sum(sum(a,b), c)
func withComposition() {
tmplInput := templateInput{
map[string]interface{}{
"a": 1,
"b": 2,
"c": 3,
"d": "something wrong",
},
}
tmpl := `{{now.Year}} sum(sum(a,b),c): {{ sum (sum (index .State "a") (index .State "b") ) (index .State "c")}}`
t, err := template.New("withState").Funcs(funcMap).Parse(tmpl)
if err != nil {
panic(err)
}
err = t.Execute(os.Stdout, tmplInput)
if err != nil {
panic(err)
}
}
func withMapState() {
state := map[string]interface{}{
"age": 10,
"name": "bob",
}
tmplInput := templateInput{
state,
}
tmpl := `{{now.Year}} {{index .State "name"}} {{ index .State "age"}}`
t, err := template.New("withState").Funcs(funcMap).Parse(tmpl)
if err != nil {
panic(err)
}
err = t.Execute(os.Stdout, tmplInput)
if err != nil {
panic(err)
}
}
func withFunction() {
td := Todo{
"Test templates",
"let's test a template to see the magic.",
time.Now(),
}
tmpl := `[{{now.UTC.Year}}][{{ .CreatedOn.Format "02-Jan-2006" }}] You have a task [{{.Name}}] description [{{.Description}}]`
t, err := template.New("todos").Funcs(funcMap).Parse(tmpl)
if err != nil {
panic(err)
}
err = t.Execute(os.Stdout, td)
if err != nil {
panic(err)
}
}
func main() {
//withFunction()
//withMapState()
//withComposition()
withAddDays()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment