Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bson.ObjectId in a template

Tags:

html

templates

go

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?

like image 450
woutr_be Avatar asked Feb 01 '15 11:02

woutr_be


2 Answers

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>
like image 163
Gustavo Niemeyer Avatar answered Sep 30 '22 00:09

Gustavo Niemeyer


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.

like image 36
Andy Xu Avatar answered Sep 30 '22 00:09

Andy Xu