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
?
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>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With