golang template使用變量

go語言中template API中變量的使用:

package main

import (
	"html/template"
	"os"
)

type ST struct {
	Status []StatusST
}

type StatusST struct {
	Status string `json:"status"`
	Num    int    `json:"sum"`
}

func main() {
	e := ST{
		Status: []StatusST{
			{Status: "ok", Num: 1},
			{Status: "error", Num: 2},
		},
	}

	tpl, err := template.New("test").Parse(`
{{ range .Status }}
	{{ $color := "red" }}
	{{ if eq .Status "ok" }} {{ $color = "green" }} {{end}}
	{{ if eq .Status "ok" }}<span style="color:{{ $color }}">{{.Num}}</span>
	{{ else if eq .Status "error" }}<span style="color:{{ $color }}">{{.Num}}</span>
	{{ end }}
{{ end }}`)
	if err != nil {
		panic(err)
	}
	err = tpl.Execute(os.Stdout, e)
	if err != nil {
		panic(err)
	}
}

其中:
{{ $var := xxx }} 是聲明變量
{{ $var = yyy }} 是給變量重新賦值
{{ $var }} 是輸出

(完)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章