1

I am outputting a dropdown list using a html template, as follows:

{{range .Organisations}}
 <option value="{{.Uuid}}">{{.Name}}</option>
{{end}}

I want to indicate that one of the items should be selected by doing an eq comparator. The only potential complication I am aware of is that the .Uuid is a *gocql.UUID, I am trying to do this:

{{range .Organisations}}
 <option value="{{.Uuid}}"{{if eq $.Contact.Organisation .Uuid}} selected="selected"{{end}}>{{.Name}}</option>
{{end}}

But it results in the following error message:

page:32:36: executing "submit_scholarship" at : error calling eq: invalid type for comparison

Any pointers in the right direction would be much appreciated.

Jay
  • 19,649
  • 38
  • 121
  • 184
  • Two suggestions. Firstly, I assume `$.Contact.Organisation` is a struct which you are comparing with whatever `Uuid` is .. I assume thats a string. Also, you may consider moving the logic here into a property of the template model itself. Then you can render `selected="selected"` only for the actual selected item .. but `selected=""` for the rest. – Simon Whitehead Nov 07 '14 at 04:32
  • Thanks, including a `Select()` function on the struct is how I normally do it. However I really want to avoid having view logic in my data model code. – Jay Nov 07 '14 at 05:35

1 Answers1

3

eq only works on basic types. You can add a custom function to do this. http://play.golang.org/p/rkYnlqmeLA

package main

import (
    "html/template"
    "os"
)

type s struct {
    Name []byte
    Uuid []byte
}

func main() {
    data := s{[]byte("aa"), []byte("aa")}

    funcMap := template.FuncMap{
        "equals": func(a []byte, b []byte) bool {
            return string(a) == string(b)
        },
    }

    var html = `{{if equals .Name .Uuid }}hi{{end}}`
    tmpl, _ := template.New("test").Funcs(funcMap).Parse(html)

    err := tmpl.Execute(os.Stdout, data)
    if err != nil {
        println(err.Error())
    }

}
chendesheng
  • 1,969
  • 18
  • 14