李恒道 发表于 2023-8-4 03:00:52

golang template.new 为什么需要name

用于使用在模板嵌套
原链接https://stackoverflow.com/questions/41176355/go-template-name

```go
tmpl := template.Must(template.New("body").Parse(`
    {{ define "body" }}
       Body
    {{ end }}
    `))

tmpl = template.Must(tmpl.New("base").Parse(`
   Start of base template

   {{ template "body" }}

   End of base template
    `))

tmpl = template.Must(tmpl.New("baz").Parse(`
   Start of baz template

   {{ template "body" }}

   End of baz template
    `))

tmpl.ExecuteTemplate(os.Stdout, "base", nil)
tmpl.ExecuteTemplate(os.Stdout, "baz", nil)
```

输出

```go
   Start of base template


       Body


   End of base template

   Start of baz template


       Body


   End of baz template
```
页: [1]
查看完整版本: golang template.new 为什么需要name