定义顶级go模板

Suppose that I have tow text files (go templates):

child.tmpl

TEXT1 
Hello {{ . }}

top.tmpl

TEXT2
{{ template "child.tmpl" "argument"}}

the child.tmpl template is nested in top.tmpl

A typical program to parse them will be :

package main

import (
    "os"
    "text/template"
)

func main() {
    t := template.Must(template.ParseFiles("child.tmpl", "top.tmpl")
    t.ExecuteTemplate(os.Stdout, "top.tmpl", nil)
}

Is there any method the pass the template to be embedded in the top-level template as an argument using the {{ . }} notation ? something like {{ template {{.}} "argument" }}

  • More generally, what is the best way to define a layout template so I can use it like a top-level template to multiple child templates ?

There are two accepted ways to solve your problem:

The first involves writing your own template-inclusion function and registering it as an template.FuncMap with your template through template.Funcs.

The other way is to use {{define xxx}} blocks in your child templates. Then you could have two different files that define the same template:

  • file1.html: {{define body}}...{{end}}
  • file2.html: {{define body}}...{{end}}

Parse the correct file depending on your needs and in your parent template just do {{template body "argument"}}.

In my opinion, the first option is more flexible.