我剛接觸golang。這是我的問(wèn)題:我想獲取template.Execute的字符串結(jié)果,并且我不想直接對(duì)http.ResponsWriter執(zhí)行這是我的代碼,它似乎無(wú)法正常工作package mainimport ( "fmt" "os" "template")type ByteSlice []bytefunc (p *ByteSlice) Write(data []byte) (lenght int, err os.Error) { *p = data return len(data), nil}func main() { page := map[string]string{"Title": "Test Text"} tpl, _ := template.ParseFile("test.html") var b ByteSlice tpl.Execute(&b, &page) fmt.Printf(`"html":%s`, b)}和text.html:<html><body> <h1>{{.Title|html}}</h1></body></html>但是我得到的是"html":</h1></body></html>
1 回答

暮色呼如
TA貢獻(xiàn)1853條經(jīng)驗(yàn) 獲得超9個(gè)贊
ByteSlice的Write方法有問(wèn)題。它應(yīng)該將新數(shù)據(jù)附加到已寫(xiě)入的數(shù)據(jù)上,但是您的版本將替換已寫(xiě)入的數(shù)據(jù)。模板代碼可能多次調(diào)用Write,因此最終只能打印出最后寫(xiě)入的內(nèi)容。
代替創(chuàng)建ByteSlice,使用bytes.Buffer。
- 1 回答
- 0 關(guān)注
- 237 瀏覽
添加回答
舉報(bào)
0/150
提交
取消