在模板中使用bson.ObjectId。

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

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 }}只会返回一个ObjectId类型,有没有办法在模板内部将其转换为字符串?

还是我必须在传递数据给template.Execute时进行转换?

英文:

I have a struct with a bson.ObjectId type, for example something like this:

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

I want to render this in an html template

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

But this obviously doesn't work since {{ Id }} would just return a ObjectId type, is there a way to convert this into a string inside the template?

Or do I have to do this when I pass data to the template.Execute?

答案1

得分: 5

bson.ObjectId 类型提供了 Hex 方法,可以返回你所需的十六进制表示。而 template 包允许你在手头上拥有的值上调用任意方法,因此没有必要将该值作为字符串存储在其他地方。

例如,可以这样使用:

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

The bson.ObjectId type offers a Hex method that will return the hex representation you are looking for, and the template package allows one to call arbitrary methods on values you have at hand, so there's no need to store that value in duplicity anywhere else as a string.

This would work, for example:

&lt;a href=&quot;/remove/{{ .Id.Hex }}&quot;&gt;Remove me&lt;/a&gt;

答案2

得分: 1

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

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

英文:

Calling id.Hex() will return a string representation of the bson.ObjectId.

This is also the default behavior if you try to marshal one bson.ObjectId to json string.

答案3

得分: 0

像这样工作playground
只需为您的模板定义点 .

{{ .Name }} {{ .Food }}
<a href="/remove/{{ .Id }}">删除我</a>
英文:

Things like to work playground
Just define dot . for your template

{{ .Name }} {{ .Food }}
&lt;a href=&quot;/remove/{{ .Id }}&quot;&gt;Remove me&lt;/a&gt;

huangapple
  • 本文由 发表于 2015年2月1日 19:53:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/28262392.html
匿名

发表评论

匿名网友

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

确定