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 }} 是输出

(完)

发布了231 篇原创文章 · 获赞 77 · 访问量 52万+

猜你喜欢

转载自blog.csdn.net/butterfly5211314/article/details/102978117