Golang語言中的Template的一些小demo

今天閒來無事,分享一下之前學習Golang中Template的一些使用和練習,大佬繞過,小白可以參考哦。 

package main

import (
	"fmt"
	"html/template"
	"os"
)

func main(){
	//f1()
//f2()
//f3()
f4()

}

func f4(){
	var textStr = `
		{{if eq "test" .vv}} 
		  vv {{ssv .vv }}
		{{else if eq "test3" .vv }} 
		vvv
		{{else}}
		vvvv
		{{end}}`

	var tf = template.FuncMap{
		"ssv":func(v string)(string){
			return v + "vvvvvv"
		},
	}

	t := template.Must(template.New("fff").Funcs(tf).Parse(textStr))
	t.Execute(os.Stdout,map[string]interface{}{
		"vv":"test",
	})
}

func f3(){
	var testStr = `
      {{range .lists}}
		 {{.}}
      {{end}}

      {{range .listsMap}}
		 {{.userName}}
      {{end}}
`
	t := template.Must(template.New("vv").Parse(testStr))
	param := make(map[string]interface{})
	param["lists"] =  []string{"張三","李四","趙武"}
	param["listsMap"] =  []map[string]interface{}{
		map[string]interface{}{"userName":"張三1"},
		map[string]interface{}{"userName":"張三2"},
		map[string]interface{}{"userName":"張三3"},
	}
	t.Execute(os.Stdout,param)
}

func f2(){
	var ttxt = `thi sis a test for tempalte:
	Name:{{.Name}}
	Age:{{.Age}}
	School:{{.School}}
	Married:{{.MarriedOK}}
`

	var ex = struct{
		Name string
		Age int
		School string
		MarriedOK bool
	}{
		Name:"小學",
		Age:18,
		School:"三大法撒旦法撒旦發送方",
		MarriedOK:true,
	}
	t := template.Must(template.New("index").Parse(ttxt))
	t.Execute(os.Stdout,ex)
}


func f1(){
	const letter = `
		Dear {{.Name}},
		{{if .Attended}}
		It was a pleasure to see you at the wedding.
		{{- else}}
		It is a shame you couldn't make it to the wedding.
		{{- end}}
		{{with .Gift -}}
		Thank you for the lovely {{.}}.
		{{end}}
		Best wishes,
		Josie
		`
	type Recep struct{
		Name,Gift string
		Attended bool
	}

	//var receipents = []Recep{
	//	{"張三","李四",true},
	//	{"哈哈","微微",false},
	//}

	var reslice = []map[string]interface{}{
		{"Name":"張三","Gift":"李四","Attended":false},
		{"Name":"哈哈","Gift":"微微","Attended":true},
	}


	t := template.Must(template.New("letter").Parse(letter))
	for _,r := range reslice {
		err := t.Execute(os.Stdout,r)
		if err != nil{
			fmt.Println("execute template :",err)
		}
	}
}

有興趣的夥伴可以在留言區留言哦,技術問題可以私信。

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