Conditional statement in GAE Go template package

0 views
Skip to first unread message

lbonn via StackOverflow

unread,
Dec 11, 2013, 8:43:52 AM12/11/13
to google-appengin...@googlegroups.com

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.



Please DO NOT REPLY directly to this email but go to StackOverflow:
http://stackoverflow.com/questions/14179359/conditional-statement-in-gae-go-template-package/14180391#14180391
Reply all
Reply to author
Forward
0 new messages