Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional statement in GAE Go template package

How is it possible to perform a conditional statement in html template in GAE GO? I was trying to accomplish this to make an option selected in a select html tag:

<select name=".Grade">
          <option value=""></option>
          <option value="1" {{ if .Grade="1" }} selected="selected" {{ end }}>Grade One</option>
          <option value="2" {{ if .Grade="2" }} selected="selected" {{ end }}>Grade Two</option>
          <option value="3" {{ if .Grade="3" }} selected="selected" {{ end }}>Grade Three</option>
          <option value="4" {{ if .Grade="4" }} selected="selected" {{ end }}>Grade Four</option>
          <option value="5" {{ if .Grade="5" }} selected="selected" {{ end }}>Grade Five</option>
          <option value="6" {{ if .Grade="6" }} selected="selected" {{ end }}>Grade Six</option>
</select>

There is

{{ if .Grade }} selected="selected" {{ end }} 

in the reference doc but this only evaluates to true if .Grade has value. Any help would be highly appreciated. Thanks!

like image 719
sagit Avatar asked Jan 06 '13 04:01

sagit


1 Answers

There is no equality statement in the base template package.
Here is an interesting discussion from golang-nuts about it.

You have several possibilities:

  • define an external function for equality, like the one Russ Cox suggests in the golang-nuts thread and test it with a if condition
  • use something the base template package can understand (see my code below)
  • remove some logic from the template: instead of having 6 hardcoded fields, you could construct a datatype with a selected boolean field and give an array of 6 of these objects to a template with a range statement

I recreated your example by using a slice of booleans:

func main() {
    temp,err := template.ParseFiles("template.html")
    if err != nil {
        panic(err)
    }

    g := make([]bool, 7)
    g[1] = true
    temp.Execute(os.Stdout, &g)
}

A line in the template looks like this:

<option value="3"{{ if index . 3 }} selected="selected"{{ end }}>Grade Three</option>

This doesn't look so good to me. But I'd say that all solutions have their drawbacks and that this is a matter of taste (the third solution should be cleaner but might be considered overkill for such a simple thing).

Edit (2013/12/11)

In Go 1.2 (released on 2013/12/01), the template engine has been updated and includes new operators, including comparison. This now should work as expected:

{{if eq .Grade 1 }} selected="selected" {{end}}

You can still choose to keep as few logic as possible in your templates, though.

like image 159
lbonn Avatar answered Oct 20 '22 00:10

lbonn