模板中的bson.ObjectId

wou*_*_be 5 html templates go

我有一个带有bson.ObjectId类型的结构,例如:

type Test struct {
     Id bson.ObjectId
     Name string
     Foo string
}
Run Code Online (Sandbox Code Playgroud)

我想在一个html模板中呈现它

{{ Name }} {{ Food }}
<a href="/remove/{{ Id }}">Remove me</a>
Run Code Online (Sandbox Code Playgroud)

但这显然不起作用,因为{{ Id }}只返回一个ObjectId类型,有没有办法将其转换为模板内的字符串?

或者,当我将数据传递给template.Execute?时,我是否必须这样做?

Gus*_*yer 5

bson.ObjectId类型提供了一种Hex方法,该方法将返回您正在查找的十六进制表示形式,并且模板包允许对您手头的值调用任意方法,因此无需在其他任何地方重复地存储该值,一个字符串。

这会起作用,例如:

<a href="/remove/{{ .Id.Hex }}">Remove me</a>
Run Code Online (Sandbox Code Playgroud)


小智 1

调用id.Hex()将返回bson.ObjectId.

bson.ObjectId如果您尝试将其封送为 json 字符串,这也是默认行为。