go - 在反引号字符串中添加字符串插值
问题描述
我试图弄清楚如何在反引号字符串文字中进行插值。
IE
myVar := "this is my var"
var jsonStr = []byte(`{
"attachments": [
{
"text": "Hello World! {{myVar}}"
}
]
}`)
{{myVar}}
这只是用来表达我的意图的伪代码,但我将如何在 golang 中做到这一点?
解决方案
您可以使用模板:
import (
"fmt"
"bytes"
"text/template"
)
func main() {
myVar := "this is my var"
var jsonStr = `{
"attachments": [
{
"text": "Hello World! {{.myVar}}"
}
]
}`
t,_:=template.New("text").Parse(jsonStr)
out:=bytes.Buffer{}
t.Execute(&out,map[string]interface{}{"myVar":myVar})
}