gpt4 book ai didi

string - text/template如何确定 map 的 "default textual representation"?

转载 作者:IT王子 更新时间:2023-10-29 01:58:41 25 4
gpt4 key购买 nike

根据 documentation Go 标准库中的 text/template 包,(据我所知,html/template 在这里是一样的)只需使用管道运算符就会吐出一个无论是什么的“默认文本表示”:

{{pipeline}}

The default textual representation of the value of the pipeline is copied to the output.

在 map 的情况下,您会得到一个很好的打印格式,其中包含键名和所有内容……顺便说一下,这是有效的 JavaScript,因此如果您愿意,可以轻松地将整个结构传递到您的 JS 代码中。

我的问题是,这个文本表示是如何确定的,更具体地说,我可以 Hook 它吗?我想也许它会检查管道是否是 fmt.Stringer 并且我可以给我的 map 子类型一个 String() string 方法,但这似乎不是是这样的。我正在寻找 text/template 代码,但我似乎不知道它是如何做到这一点的。

text/template 如何确定“默认文本表示”?

最佳答案

默认文本表示由 fmt 的方式决定包打印值。所以你找对了树。

看这个例子:

t := template.Must(template.New("").Parse("{{.}}"))
m := map[string]interface{}{"a": "abc", "b": 2}
t.Execute(os.Stdout, m)

输出:

map[a:abc b:2]

现在,如果我们使用带有 String() 方法的自定义 map 类型:

type MyMap map[string]interface{}

func (m MyMap) String() string { return "custom" }

mm := MyMap{"a": "abc", "b": 2}
t.Execute(os.Stdout, mm)

输出是:

custom

Go Playground 上尝试这些(以及下面的示例) .

需要注意什么?

请注意 MyMap.String() 有一个值接收器(不是指针)。我传递了 MyMap 的值,所以它起作用了。如果您将接收器类型更改为指向 MyMap 的指针,它将不起作用。这是因为只有 *MyMap 类型的值才有 String() 方法,而 MyMap 的值没有。

如果 String() 方法有一个指针接收者,你必须传递 &mm (*MyMap 类型的值)如果你希望您的自定义表示起作用。

另请注意,在 html/template 的情况下,模板引擎会进行上下文转义,因此 fmt 包的结果可能会进一步转义。

例如,如果您的自定义 String() 方法会返回“不安全”的内容:

func (m MyMap2) String() string { return "<html>" }

尝试插入:

mm2 := MyMap2{"a": "abc", "b": 2}
t.Execute(os.Stdout, mm2)

被转义:

&lt;html&gt;

实现

这是在 text/template 中实现的地方包裹:text/template/exec.go ,未导出函数 state.PrintValue(),当前行 #848:

_, err := fmt.Fprint(s.wr, iface)

如果您使用的是 html/template包,它在 html/template/content.go 中实现,未导出函数 stringify(),当前行 #135:

return fmt.Sprint(args...), contentTypePlain

更多选项

另请注意,如果该值实现了 error , Error() 方法将被调用并且它优先于 String():

type MyMap map[string]interface{}

func (m MyMap) Error() string { return "custom-error" }

func (m MyMap) String() string { return "custom" }

t := template.Must(template.New("").Parse("{{.}}"))
mm := MyMap{"a": "abc", "b": 2}
t.Execute(os.Stdout, mm)

将输出:

custom-error

而不是自定义。在 Go Playground 上试用.

关于string - text/template如何确定 map 的 "default textual representation"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38518866/

25 4 0