Created
February 14, 2024 07:24
-
-
Save patrickbucher/5fab371416d20dd4fe3c639a576c0678 to your computer and use it in GitHub Desktop.
Trying out Go Templates
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" | |
"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