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)
		}
	}
}

有兴趣的伙伴可以在留言区留言哦,技术问题可以私信。

你可能感兴趣的:(GO)