Conditionalshtml
if, else, with, or & and provide the framework for handling conditional logic in Go Templates. Like range, each statement is closed with end.ide
Go Templates treat the following values as false:this
Example 1: ifcode
{{ if isset .Params "title" }}<h4>{{ index .Params "title" }}</h4>{{ end }}
Example 2: if … elsehtm
{{ if isset .Params "alt" }} {{ index .Params "alt" }} {{else}} {{ index .Params "caption" }} {{ end }}
Example 3: and & or對象
{{ if and (or (isset .Params "title") (isset .Params "caption")) (isset .Params "attr")}}
Example 4: withip
An alternative way of writing 「if」 and then referencing the same value is to use 「with」 instead. with rebinds the context . within its scope, and skips the block if the variable is absent.ci
The first example above could be simplified as:element
{{ with .Params.title }}<h4>{{ . }}</h4>{{ end }}
Example 5: if … else ifget
{{ if isset .Params "alt" }} {{ index .Params "alt" }} {{ else if isset .Params "caption" }} {{ index .Params "caption" }} {{ end }}
Example 1: Using Context
{{ range array }} {{ . }} {{ end }}
Example 2: Declaring value variable name
{{range $element := array}} {{ $element }} {{ end }}
Example 2: Declaring key and value variable name
{{range $index, $element := array}} {{ $index }} {{ $element }} {{ end }}
package main import ( "fmt" "html/template" "log" "net/http" ) type User struct { name string } func (this *User) GetName() string { return this.name } func test(w http.ResponseWriter, r *http.Request) { user := &User{ name: "hello world!", } m := map[string]interface{}{ "user": user, } t, err := template.ParseFiles("views/test.tpl") if err != nil { fmt.Println("parseFiles:", err) return } t.Execute(w, m) } func main() { http.HandleFunc("/", test) err := http.ListenAndServe(":9090", nil) if err != nil { log.Fatal("listenAndServe:", err) } }
如今map中有一個user對象,想在模板中調用user.GetName():
<div> {{.user.GetName}} </div>