documentation 声明 template 指令有两种形式:
{{template "name"}}
执行指定名称的模板
零数据。
{{template "name" pipeline}}
具有指定名称的模板是
执行时将点设置为管道的值。
后者接受一个管道语句,然后在执行的模板中将其值设置为dot 值。所以调用
{{template "partial1" "string1"}}
将在partial1 模板中将{{.}} 设置为"string1"。因此,虽然无法在部分中设置名称foo,但您可以传递参数,它们将出现在. 中。示例:
模板.html
<div>
{{ template "partial1.html" "muh"}} // how do I pass foo param here??
</div>
partial1.html
{{if eq . "muh"}}
blep
{{else}}
moep
{{end}}
main.go
import (
"html/template"
"fmt"
"os"
)
func main() {
t,err := template.ParseFiles("template.html", "partial1.html")
if err != nil { panic(err) }
fmt.Println(t.Execute(os.Stdout, nil))
}
运行此程序将打印模板的内容,其中包含来自部分的blep。更改传递的值将更改此行为。
您还可以分配变量,因此可以在部分中将. 分配给foo:
{{ $foo := . }}