6

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?

woutr_be
  • 9,532
  • 24
  • 79
  • 129

3 Answers3

5

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>
Gustavo Niemeyer
  • 22,007
  • 5
  • 57
  • 46
  • This is correct. While generating a new Object ID, you could call bson.NewObjectId().Hex() and get the string only - in case you later want to insert that to a database and you use string type _id fields – Gaurav Ojha Sep 09 '16 at 10:16
1

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.

Andy Xu
  • 1,107
  • 8
  • 10
  • How would this work if I'm using this in a template? `Id.Hex()` doesn't seem to be accepted – woutr_be Feb 02 '15 at 07:28
  • @woutr_be try to pass the string when you call `template.Execute`? – Andy Xu Feb 02 '15 at 08:23
  • The problem that I'm having is that the `Id` in my struct is defined as a `bson.ObjectId`, so if I use `.Hex()` on it, it won't match the type anymore. Not sure what the solution for that is – woutr_be Feb 02 '15 at 14:22
  • the only solution I found so far was to add a new parameter in my struct `String_id string`, which works fine. Although not sure if it's the best solution. – woutr_be Feb 03 '15 at 03:36
  • @woutr_be Could you please be more specific how to add this `String_id string` ? in the retrieved data structure? won't that influence the result stored in db when insert data with that? – armnotstrong Mar 12 '15 at 09:55
  • You should be able to just use {{.Id.Hex}} in the template to call that method. E.g. see https://play.golang.org/p/NfZ-Jv7Ck3. See the [documentation](https://golang.org/pkg/text/template/#hdr-Arguments). – Dave C Mar 12 '15 at 19:11
0

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

{{ .Name }} {{ .Food }}
<a href="/remove/{{ .Id }}">Remove me</a>
Uvelichitel
  • 8,220
  • 1
  • 19
  • 36
  • Hmm, this doesn't seem to work when using it in a loop though `{{ .$value.Rating.Id }}` – woutr_be Feb 01 '15 at 16:40
  • FYI, just using `{{ $value.Rating.Id }}` prints out: `ObjectIdHex("54ce0e86d2b38b9d26000001")` and not the actual string – woutr_be Feb 02 '15 at 15:26