Add template

This commit is contained in:
Sangeeth Sudheer 2024-05-01 20:51:49 +05:30
parent 7fc76bdb93
commit 774faa3ea4
Signed by: x
GPG Key ID: F6D06ECE734C57D1
2 changed files with 47 additions and 2 deletions

View File

@ -23,7 +23,8 @@ package main
// import "git.sangeeth.dev/gobyexample/defers" // import "git.sangeeth.dev/gobyexample/defers"
// import "git.sangeeth.dev/gobyexample/recovering" // import "git.sangeeth.dev/gobyexample/recovering"
// import "git.sangeeth.dev/gobyexample/stringfuncs" // import "git.sangeeth.dev/gobyexample/stringfuncs"
import "git.sangeeth.dev/gobyexample/formatting" // import "git.sangeeth.dev/gobyexample/formatting"
import "git.sangeeth.dev/gobyexample/templates"
func main() { func main() {
// runes.Runes() // runes.Runes()
@ -49,5 +50,6 @@ func main() {
// defers.Defers() // defers.Defers()
// recovering.Recover() // recovering.Recover()
// stringfuncs.StringFuncs() // stringfuncs.StringFuncs()
formatting.Formatting() // formatting.Formatting()
templates.Templates()
} }

43
templates/templates.go Normal file
View File

@ -0,0 +1,43 @@
package templates
import (
"fmt"
"os"
"strings"
"text/template"
)
func CreateTemplate(label, content string) *template.Template {
return template.Must(template.New(label).Parse(content))
}
func Templates() {
t1 := CreateTemplate("bioList", `
<dl>
{{range . -}}
<dt>{{ .Name }}</dt>
<dd>
<p>{{ .Bio }}</p>
<p>{{ if .IsAdult -}} Adult {{- else -}} Teen {{- end }}</p>
</dd>
{{end}}
</dl>
`)
peeps := []struct {
Name, Bio string
Age uint
IsAdult bool
}{
{"Paul Atreides", "Duke of Arrakis, Lisan Al Gaib", 24, true},
{"Leto Atreides", "Former Duke of Arrakis and father of Paul Atreides", 43, true},
{"Hidenori", "Unrelated character from DLoHB", 16, false},
}
t1.Execute(os.Stdout, peeps)
var b strings.Builder
t1.Execute(&b, peeps)
output := fmt.Sprintf("<body>\n%s</body>\n", b.String())
fmt.Println("Output as follows:")
fmt.Println(output)
}