go pkg "html/template" 中实现类似于PHP的ob_start(), ob_get_clean()

2013-12-18 13:47:22 +08:00
 fansekey
最近在研究如果template中获取两个自定义函数之间的内容。比如;

```
<html>
<head></head>
<body>
{{ob_start "script"}}
function test() {
console.log("hello, World!");
}
test();
{{ob_end}}
</body>
</html>
```
我可以在 ob_end 这个函数中获取到中间夹的JS代码。

尝试了各种方式后,得到一个比较靠谱的方法。就算抛砖引玉了

```
package main

import (
"bytes"
"fmt"
"html/template"
)

func main() {

buf := bytes.NewBufferString("")
var o_pos int
var funcMap = map[string]interface{}{
"ob_start": func() string {
o_pos = buf.Len()
return ""
},

"ob_end": func() string {
byte_buf := buf.Bytes()
//seek -n
buf.Truncate(o_pos)
bf := bytes.NewBuffer(byte_buf[o_pos:])

//get it
fmt.Println(bf)

return bf.String()
},
}

tmpl := template.Must(template.New(`template`).Funcs(funcMap).Parse(`<html>{{ob_start}}fdsafdaafa中国{{ob_end}}</html>`))
tmpl.Execute(buf, "")
fmt.Println(buf)
}
```
1554 次点击
所在节点    Go 编程语言
0 条回复

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/93631

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX