Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
String 如何保存渲染模板而不是打印到os.Stdout?_String_Templates_Go_Go Templates - Fatal编程技术网

String 如何保存渲染模板而不是打印到os.Stdout?

String 如何保存渲染模板而不是打印到os.Stdout?,string,templates,go,go-templates,String,Templates,Go,Go Templates,我是新来的。我一直在搜索文档。在下面的代码中,它正在屏幕上渲染和打印它。我希望呈现的文本以字符串形式存储,以便可以从函数返回它 package main import ( "os" "text/template" ) type Person struct { Name string //exported field since it begins with a capital letter } func main() { t := template.Ne

我是新来的。我一直在搜索文档。在下面的代码中,它正在屏幕上渲染和打印它。我希望呈现的文本以字符串形式存储,以便可以从函数返回它

package main

import (
    "os"
    "text/template"
)

type Person struct {
    Name string //exported field since it begins with a capital letter
}



func main() {
    t := template.New("sammple") //create a new template with some name
    t, _ = t.Parse("hello {{.Name}}!") //parse some content and generate a template, which is an internal representation

    p := Person{Name:"Mary"} //define an instance with required field
    t.Execute(os.Stdout, p) //merge template ‘t’ with content of ‘p’
}


如何操作?

只需将其渲染到内存缓冲区中,例如(或添加到Go 1.10中),您可以通过调用其(或)方法将其内容作为
字符串获取:

这将再次打印(在上尝试):

但这次这是
s
字符串变量的值

使用
strings.Builder()
,您只需更改此行:

buf := &strings.Builder{}
试一试这个


请参阅相关问题:

只需将其渲染到内存缓冲区中,例如(或添加到Go 1.10中),通过调用其(或)方法,您可以将其内容作为
字符串获取:

这将再次打印(在上尝试):

但这次这是
s
字符串变量的值

使用
strings.Builder()
,您只需更改此行:

buf := &strings.Builder{}
试一试这个

见相关问题:

buf := &strings.Builder{}