我正在尝试转换 golang 模板,如果找不到匹配项,则允许忽略。那可能吗?
package main
import (
"bytes"
"fmt"
"text/template"
)
type Person struct {
Name string
Age int
}
type Info struct {
Name string
Id int
}
func main() {
msg := "Hello {{ .Id }} With name {{ .Name }}"
p := Person{Name: "John", Age: 24}
i := Info{Name: "none", Id: 5}
t := template.New("My template")
t, _ = t.Parse(msg)
buf := new(bytes.Buffer)
t.Execute(buf, p)
fmt.Println(buf.String())
buf = new(bytes.Buffer)
t.Execute(buf, i)
fmt.Println(buf.String())
}
我想打印这个
Hello {{ .Id }} with name John
Hello 5 With name none