Convert byte array to string in Golang template

huangapple go评论73阅读模式
英文:

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 }}

`)

huangapple
  • 本文由 发表于 2021年11月30日 00:39:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/70158149.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定