英文:
Convert byte array to string in Golang template
问题
在Go模板中,如何将字节数组转换为字符串?我访问的上下文值在打印时看起来像这样:
[34 102 111 111 34]
这对应于"foo"
。
当我打印值的类型(通过printf "%T" .MyValue
)时,我看到的是json.RawMessage
,它是一个[]byte
类型。
英文:
In a Go template, how can I convert a byte array to a string? One the context values I'm accessing looks like this when I print it:
[34 102 111 111 34]
This corresponds to "foo"
.
When I print the type of the value (by doing printf "%T" .MyValue
), I see json.RawMessage
, which is a []byte
.
答案1
得分: 8
你可以使用内置的 printf
模板函数和 %s
动词。
{{ printf "%s" .MyValue }}
如果你想避免使用 printf
,你也可以添加自己的函数。
t, err := template.New("t").Funcs(template.FuncMap{
"btoa": func(b []byte) string { return string(b) },
}).Parse(`
{{ btoa .MyValue }}
`)
英文:
You can use the builtin printf
template function and the %s
verb.
{{ printf "%s" .MyValue }}
You can also add your own function if you want to avoid printf
for some reason.
t, err := template.New("t").Funcs(template.FuncMap{
"btoa": func(b []byte) string { return string(b) },
}).Parse(`
{{ btoa .MyValue }}
`)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论