bson.ObjectId 在模板中

bson.ObjectId in a template

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

type Test struct {
     Id bson.ObjectId
     Name string
     Foo string
}

我想在 html 模板中呈现它

{{ Name }} {{ Food }}
<a href="/remove/{{ Id }}">Remove me</a>

但这显然行不通,因为 {{ Id }} 只是 return ObjectId 类型,有没有办法将其转换为模板内的字符串?

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

工作喜欢的东西playground 只需为您的模板定义点 .

{{ .Name }} {{ .Food }}
<a href="/remove/{{ .Id }}">Remove me</a>

调用 id.Hex() 将 return bson.ObjectId 的字符串表示形式。

如果您尝试将一个 bson.ObjectId 编组为 json 字符串,这也是默认行为。

bson.ObjectId type offers a Hex method that will return the hex representation you are looking for, and the template 程序包允许对您手头的值调用任意方法,因此无需将该值以字符串的形式存储在其他任何地方。

这会起作用,例如:

<a href="/remove/{{ .Id.Hex }}">Remove me</a>