如何获取模板渲染的结果

huangapple go评论86阅读模式
英文:

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 (
    &quot;fmt&quot;
    &quot;os&quot;
    &quot;template&quot;
)

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{&quot;Title&quot;: &quot;Test Text&quot;}
    tpl, _ := template.ParseFile(&quot;test.html&quot;)
    var b ByteSlice
    tpl.Execute(&amp;b, &amp;page)
    fmt.Printf(`&quot;html&quot;:%s`, b)
}

And the text.html:

&lt;html&gt;
&lt;body&gt;
    &lt;h1&gt;{{.Title|html}}&lt;/h1&gt;
&lt;/body&gt;
&lt;/html&gt;

But what I got is

&quot;html&quot;:&lt;/h1&gt;
&lt;/body&gt;
&lt;/html&gt;

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

huangapple
  • 本文由 发表于 2011年12月23日 05:13:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/8609780.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定