Templates 如何获得模板渲染的结果

Templates 如何获得模板渲染的结果,templates,go,Templates,Go,我是刚来戈兰的新手 这是我的问题:我想得到template.Execute的字符串结果,但我不想直接将其执行到http.writer 这是我的代码,它似乎工作不好 package main import ( "fmt" "os" "template" ) type ByteSlice []byte func (p *ByteSlice) Write(data []byte) (lenght int, err os.Error) { *p = data

我是刚来戈兰的新手

这是我的问题:我想得到template.Execute的字符串结果,但我不想直接将其执行到http.writer

这是我的代码,它似乎工作不好

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)
}
以及text.html:

<html>
<body>
    <h1>{{.Title|html}}</h1>
</body>
</html>

{{.Title | html}
但我得到的是

"html":</h1>
</body>
</html>
“html”:

ByteSlice的写入方法有缺陷。它应该将新数据附加到已经写入的数据中,但您的版本会替换已经写入的数据。模板代码调用可能会多次写入,因此最终只打印最后写入的内容

不要创建ByteSlice,而是使用