dongzong2017 2016-10-20 21:31
浏览 5

捕获golang模板输出或将其分配给变量

Within a template, how can I achieve this?

{{$var := template "my-template"}}

I just get "unexpected <template> in operand".

  • 写回答

1条回答 默认 最新

  • dongshuzhuo5659 2016-10-21 07:42
    关注

    There is no "builtin" action for getting the result of a template execution, but you may do it by registering a function which does that.

    You can register functions with the Template.Funcs() function, you may execute a named template with Template.ExecuteTemplate() and you may use a bytes.Buffer as the target (direct template execution result into a buffer).

    Here is a complete example:

    var t *template.Template
    
    func execTempl(name string) (string, error) {
        buf := &bytes.Buffer{}
        err := t.ExecuteTemplate(buf, name, nil)
        return buf.String(), err
    }
    
    func main() {
        t = template.Must(template.New("").Funcs(template.FuncMap{
            "execTempl": execTempl,
        }).Parse(tmpl))
        if err := t.Execute(os.Stdout, nil); err != nil {
            panic(err)
        }
    }
    
    const tmpl = `{{define "my-template"}}my-template content{{end}}
    See result:
    {{$var := execTempl "my-template"}}
    {{$var}}
    `
    

    Output (try it on the Go Playground):

    See result:
    
    my-template content
    

    The "my-template" template is executed by the registered function execTempl(), and the result is returned as a string, which is stored in the $var template variable, which then is simply added to the output, but you may use it to pass to other functions if you want to.

    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度