1 개요[ | ]
- Go text/template
2 예시 1[ | ]
Go
Copy
package main
import (
"log"
"os"
"text/template"
)
type Recipient struct {
Name, Gift string
Attended bool
}
func main() {
const letter = `
Dear {{.Name}},
{{if .Attended}}
It was a pleasure to see you at the wedding.
{{- else}}
It is a shame you couldn't make it to the wedding.
{{- end}}
{{with .Gift -}}
Thank you for the lovely {{.}}.
{{end}}
Best wishes,
Josie
`
var recipient = Recipient{"Aunt Mildred", "bone china tea set", true}
t := template.Must(template.New("letter").Parse(letter))
err := t.Execute(os.Stdout, recipient)
if err != nil {
log.Println("executing template:", err)
}
}
Loading
3 예시 2[ | ]
Go
Copy
package main
import (
"os"
"text/template"
)
var card1 = map[int]string{1: "S", 2: "H", 3: "C", 4: "D"}
var card2 = map[string]string{"a": "S", "b": "H", "c": "C", "d": "D"}
func check(err error) {
if err != nil {
panic(err)
}
}
func main() {
t := template.Must(template.New("t1").Parse("Dot:{{.}}\n"))
check(t.Execute(os.Stdout, card1))
t = template.Must(template.New("t2").Parse("Hi,{{.a}}\n"))
check(t.Execute(os.Stdout, card2))
t = template.Must(template.New("t2").Parse("{{index . 3}}\n"))
check(t.Execute(os.Stdout, card1))
t = template.Must(template.New("t2").Parse(`Repeat
{{define "T1"}}Apple{{end}} {{define "T2"}}Ape{{end}}
{{template "T2"}} ate {{template "T1"}}
`))
check(t.Execute(os.Stdout, card1))
}
Loading
4 예시 3[ | ]
Go
Copy
package main
import (
"bytes"
"fmt"
"strings"
"text/template"
)
func renderTemplate(tmplString string, labels map[string]string) string {
var buf bytes.Buffer
t, _ := template.New("t1").Parse(strings.ReplaceAll(tmplString, "$labels", ""))
_ = t.Execute(&buf, labels)
return buf.String()
}
func main() {
tmplString := "{{$labels.instance}} of job {{$labels.job}} has been down for more than 5 minutes."
labels := map[string]string{"instance": "😋", "job": "👌"}
result := renderTemplate(tmplString, labels)
fmt.Println(result)
}
Loading
5 참고[ | ]
편집자 Jmnote
로그인하시면 댓글을 쓸 수 있습니다.