2015-05-16 50 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

相關問題