如何获得模板渲染的结果

Tia*_*hen 2 templates go

我是golang的新手.

这是我的问题:我想得到一个template.Execute的字符串结果,我不想直接执行它到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)
}
Run Code Online (Sandbox Code Playgroud)

和text.html:

<html>
<body>
    <h1>{{.Title|html}}</h1>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

但我得到的是

"html":</h1>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

Eva*_*haw 5

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

而不是创建ByteSlice,使用bytes.Buffer.