V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
fansekey
V2EX  ›  Go 编程语言

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

  •  
  •   fansekey · 2013-12-18 13:47:22 +08:00 · 1547 次点击
    这是一个创建于 3775 天前的主题,其中的信息可能已经有所发展或是发生改变。
    最近在研究如果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)
    }
    ```
    目前尚无回复
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3057 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 757ms · UTC 11:00 · PVG 19:00 · LAX 04:00 · JFK 07:00
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.