3 回答

TA貢獻1824條經(jīng)驗 獲得超8個贊
作為對此的說明和跟進,我最終得到了這個問題的兩個主要答案:1)盡量避免這種情況。在某些情況下,一個簡單的 if 語句工作正常。2)我能夠使用 FuncMap 中的一個函數(shù)來完成這個,它只是一個單獨的渲染。這不是世界上最偉大的事情,但它確實有效并解決了問題。這是一個完整的獨立演示,展示了這個想法:
package main
import (
"bytes"
"html/template"
"os"
)
func main() {
var err error
// our main template here calls a sub template
tpl := template.New("main")
// provide a func in the FuncMap which can access tpl to be able to look up templates
tpl.Funcs(map[string]interface{}{
"CallTemplate": func(name string, data interface{}) (ret template.HTML, err error) {
buf := bytes.NewBuffer([]byte{})
err = tpl.ExecuteTemplate(buf, name, data)
ret = template.HTML(buf.String())
return
},
})
// this is the main template
_, err = tpl.Parse(`
{{$Name := "examplesubtpl"}}
from main template
{{CallTemplate $Name .}}
`)
if err != nil {
panic(err)
}
// whatever code to dynamically figure out what templates to load
// a stub just to demonstrate
_, err = tpl.New("examplesubtpl").Parse(`
this is from examplesubtpl - see, it worked!
`)
if err != nil {
panic(err)
}
err = tpl.Execute(os.Stdout, map[string]interface{}{})
if err != nil {
panic(err)
}
}
- 3 回答
- 0 關注
- 220 瀏覽
添加回答
舉報