英文:
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:
<a href="/remove/{{ .Id.Hex }}">Remove me</a>
答案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 }}
<a href="/remove/{{ .Id }}">Remove me</a>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论