go 内置的模板引擎库text/template,在实际开发中一般用的是html/template
package main
import (
"fmt"
"os"
"text/template"
)
func main() {
tmpl := `This is the first template string, {{ .message }}`
te, err := template.New("texTmpl").Parse(tmpl)
if err != nil {
fmt.Println(err)
return
}
data := map[string]any{
"message": "hello world!",
}
execErr := te.Execute(os.Stdout, data)
if execErr != nil {
fmt.Println(err)
}
}
上述代码的输出为:This is the first template string, hello world!
在案例代码中,tmpl是一个模板字符串,字符串中的{{ .message }}是模板引擎的模板参数。首先通过*Template.Parse方法解析模板字符串,
func (t *Template) Parse(text string) (*Template, error)
解析成功后再通过*Template.Execute方法将data数据应用于模板中,最后输出到传入的Writer中也就是os.Stdout。
func (t *Template) Execute(wr io.Writer, data any) error
在以后模板引擎的使用中,基本上都是这三步:
- 获取模板
- 解析模板,
- 将数据应用到模板中
posted on
浙公网安备 33010602011771号