英文:
how to get the result of template-rendering
问题
我在golang中还是很新手。
这是我的问题:我想要得到模板执行的字符串结果,而不想直接执行到http.ResponsWriter。
这是我的代码,但似乎不起作用:
package main
import (
"fmt"
"os"
"template"
)
type ByteSlice []byte
func (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)
}
而test.html的内容如下:
<html>
<body>
<h1>{{.Title|html}}</h1>
</body>
</html>
但是我得到的结果是:
"html":</h1>
</body>
</html>
英文:
I'm quite new in golang.
Here is my problem: I want to get the string result of a template.Execute, and I don't want to execute it directly to a http.ResponsWriter
Here is my code and it does not seem to work well
package main
import (
"fmt"
"os"
"template"
)
type ByteSlice []byte
func (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)
}
And the text.html:
<html>
<body>
<h1>{{.Title|html}}</h1>
</body>
</html>
But what I got is
"html":</h1>
</body>
</html>
答案1
得分: 6
ByteSlice的Write方法有bug。它应该将新数据追加到已经写入的数据中,但是你的版本替换了已经写入的数据。很可能模板代码会多次调用Write,所以你最终只会打印出最后一次写入的内容。
不要使用ByteSlice,而是使用bytes.Buffer。
英文:
ByteSlice's Write method is buggy. It should append the new data to what's already been written, but your version replaces the already written data. It's likely that the template code calls Write more than once, so you only end up printing the last thing that was written.
Instead of creating ByteSlice, use bytes.Buffer.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论