【问题标题】:How can I render a template in Go without any variables?如何在没有任何变量的情况下在 Go 中渲染模板?
【发布时间】:2013-06-11 05:26:58
【问题描述】:

我已使用以下代码将模板文件加载到内存中:

t := template.New("master")
tpl, err := t.ParseFiles("templates/index.html")

现在我想将该模板绘制成一个字符串,所以我的index.html 很空:

{{define "master"}}
Hello World
{{end}}

我刚刚开始,所以我还没有任何数据。有没有办法可以将Template 对象转换为没有数据的字符串?

【问题讨论】:

    标签: go


    【解决方案1】:

    如果您的模板(尚未)使用任何变量,您可以将 any 值作为数据传递以呈现模板。因此,要将模板渲染到标准输出,您可以使用:

    tpl.Execute(os.Stdout, nil)
    

    如果你真的想将模板渲染成字符串,可以使用bytes.Buffer作为中介:

    var buf bytes.Buffer
    tpl.Execute(&buf, nil)
    str := buf.String()
    

    【讨论】:

      【解决方案2】:

      按照设计,这在 Go 中是不可能的 - 如果您没有数据,则 Template 包是不必要的开销。

      如果您没有数据,只需使用io 包读取文件,而不是使用模板。

      【讨论】:

        猜你喜欢
        • 2020-06-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-01-30
        • 2019-09-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多