2015-05-16 49 views
4
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" . }} 

没有输出,没有错误。Golang:使用{{template“partial.html”的先决条件是什么? }}

如果我删除这两行{{template“...”。 }},我可以看到该部分是输出。

需要什么才能使{{template“...”。 }}工作还是我完全误解了html /模板?

+1

它*看起来像*你可能假设'模板'行动可以采取一个文件名;它不能。它指的是已经解析过的命名模板(通过'template.Parse ...','someOtherTemplate.Parse ...'或者通过解析模板的'define'动作)。请参阅'text/template'包文档的[“关联模板”](https://golang.org/pkg/text/template/#hdr-Associated_templates)部分。 –

+0

@DaveC此链接http://gohugo.io/templates/go-templates/似乎暗示它可以;但是它来自谷歌搜索,我不知道这是否是hugo添加的一些语法suger。 – Shawn

+1

可能重复[golang模板 - 如何呈现模板?](http://stackoverflow.com/questions/19546896/golang-template-how-to-render-templates) – Shawn

回答

9

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

login.tmpl

{{define "login"}} 
<!doctype html> 
<html lang="en"> 
.. 
{{template "header" .}} 
</body> 
</html> 
{{end}} 

header.tmpl

{{define "header"}} 
whatever 
{{end}} 

然后,解析这两个文件

template.Must(template.ParseFiles("login.tmpl", "header.tmpl")) 

,然后与定义的名称执行模板:

template.ExecuteTemplate(os.Stdout, "login", data) 
+0

t:= template.Must(template.ParseFiles (“login.tmpl”,“header.tmpl”)); t.ExecuteTemplate(os.Stdout,“登录”,数据) – Sairam

相关问题