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>
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.