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!
There is no equality statement in the base template package.
Here is an interesting discussion from golang-nuts about it.
You have several possibilities:
if
conditionselected
boolean field and give an array of 6 of these objects to a template with a range
statementI 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With