Bson.ObjectId in the template

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

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

I want to do this in an html template

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

But this obviously does not work, since {{ Id }} will simply return the ObjectId type, is there any way to convert it to a string inside the template?

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

+4
html go templates
source share
3 answers

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

This is also the default behavior if you try to bson.ObjectId one line of bson.ObjectId in json.

0
source share

type bson.ObjectId offers a Hex that will return the hexadecimal representation you are looking for, and the template package allows you to call arbitrary methods according to your values, so there is no need to store this value in duplicate elsewhere as a string.

This will work, for example:

 <a href="/remove/{{ .Id.Hex }}">Remove me</a> 
+2
source share

Things like to work the playground. Just point the point . for your template

 {{ .Name }} {{ .Food }} <a href="/remove/{{ .Id }}">Remove me</a> 
0
source share

All Articles