Golang:使用{{template"partial.html"的先决条件是什么.}}

Sha*_*awn 5 templates go

import "os"    
import "html/template"
...    
t, _ := template.ParseFiles("login.html")
t.Execute(os.Stdout, data)
...
login.html:

{{ template "header.html" . }}
<form ....>...</form>
{{ template "footer.html" . }}
Run Code Online (Sandbox Code Playgroud)

没有输出,没有错误.

如果我删除{{template"......"这两行.我可以看到这部分被输出了.

需要做什么{{模板"......".工作还是我完全误解了html /模板?

pra*_*ram 13

您需要为包含其他模板的文件定义名称,然后执行该名称.

login.tmpl

{{define "login"}}
<!doctype html>
<html lang="en">
..
{{template "header" .}}
</body>
</html>
{{end}}
Run Code Online (Sandbox Code Playgroud)

header.tmpl

{{define "header"}}
whatever
{{end}}
Run Code Online (Sandbox Code Playgroud)

然后你解析这两个文件

template.Must(template.ParseFiles("login.tmpl", "header.tmpl"))
Run Code Online (Sandbox Code Playgroud)

然后使用定义的名称执行模板:

template.ExecuteTemplate(os.Stdout, "login", data)
Run Code Online (Sandbox Code Playgroud)