Skip to content

Instantly share code, notes, and snippets.

@patrickbucher
Created February 14, 2024 07:24
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 patrickbucher/5fab371416d20dd4fe3c639a576c0678 to your computer and use it in GitHub Desktop.
Save patrickbucher/5fab371416d20dd4fe3c639a576c0678 to your computer and use it in GitHub Desktop.
Trying out Go Templates
package main
import (
"os"
"text/template"
"time"
)
type Article struct {
Title string
Subtitle string
Author string
Published time.Time
Language string
}
func (a Article) PublishedStr() string {
switch a.Language {
case "de":
return a.Published.Format("01.02.2006 15:04")
default:
return a.Published.Format("2006-02-01 15:04")
}
}
var Examples = []Article{
{"Hello", "My First Post", "Patrick Bucher", time.Now(), "en"},
{"Shalom", "Greetings", "Shlomo Shekelstein", time.Now(), "en"},
{"Hallo", "Ein weiterer Beitrag", "Patrick Bucher", time.Now(), "de"},
}
const blogTemplate = `
{{ define "article" }}
{{ .Title }}. {{ .Subtitle }}
{{ .Author }}, {{ .PublishedStr }} ({{ .Language }})
{{ end }}
{{ range $i, $article := . }}
{{- inc $i }}) {{- template "article" $article -}}
{{ end }}
`
func main() {
funcs := template.FuncMap{
"inc": func(i int) int { return i + 1 },
}
bt, err := template.New("blog").Funcs(funcs).Parse(blogTemplate)
if err != nil {
panic(err)
}
err = bt.Execute(os.Stdout, Examples)
if err != nil {
panic(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment