go實踐二十四 使用模板

編輯一個 testtemplate.go 文件,內容如下

使用 go run testtemplate.go 運行該文件即可

package main

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


func main() {
	fmt.Fprintf(os.Stdout,"%v\n","testtemplate")
	testtemplate()

	fmt.Fprintf(os.Stdout,"\n")
	fmt.Fprintf(os.Stdout,"\n")
	fmt.Fprintf(os.Stdout,"%v\n","testforeach")
	testforeach()

	fmt.Fprintf(os.Stdout,"\n")
	fmt.Fprintf(os.Stdout,"%v\n","testcondition")
	testcondition()

	fmt.Fprintf(os.Stdout,"\n")
	fmt.Fprintf(os.Stdout,"%v\n","testtemplatevar")
	testtemplatevar()
}


type Person struct {
	UserName string
	email string //未導出的字段,首字母是小寫的
}
func testtemplate(){
	t := template.New("fieldname example")
	t,_ = t.Parse("hello {{.UserName}}! email: {{.email}}")
	p := Person{
		UserName:"template",
	}
	t.Execute(os.Stdout,p)
}

/*
輸出嵌套字段內容
上面我們例子展示瞭如何針對一個對象的字段輸出,那麼如果字段裏面還有對象,如何來循環的輸出這些內容呢?我們可以使用{{with …}}…{{end}}和{{range …}}{{end}}來進行數據的輸出。

{{range}} 這個和Go語法裏面的range類似,循環操作數據
{{with}}操作是指當前對象的值,類似上下文的概念
*/
type Friend struct {
	Fname string
}
type PersonForeach struct {
	UserName string
	Emails []string
	Friends []*Friend
}
func testforeach(){
	f1 := Friend{Fname:"friend1"}
	f2 := Friend{Fname:"friend2"}
	t := template.New("testforeach")
	t,_ = t.Parse(`hello {{.UserName}}!
{{range .Emails}}
an email {{.}}
{{end}}
{{with .Friends}}
{{range .}}
my friend name is {{.Fname}}
{{end}}
{{end}}
`)
	p := PersonForeach{
		UserName:"hello world",
		Emails:[]string{"[email protected]","[email protected]"},
		Friends:[]*Friend{&f1,&f2},
	}
	t.Execute(os.Stdout,p)
}

/*
在Go模板裏面如果需要進行條件判斷,那麼我們可以使用和Go語言的if-else語法類似的方式來處理,如果pipeline爲空,那麼if就認爲是false,下面的例子展示瞭如何使用if-else語法:
注意:if裏面無法使用條件判斷,例如.Mail=="[email protected]",這樣的判斷是不正確的,if裏面只能是bool值
*/
func testcondition(){
	tE := template.New("empty template")
	tE = template.Must(tE.Parse("空 pipeline if demo: {{if ``}} 不會輸出. {{end}} \n"))
	tE.Execute(os.Stdout,nil)

	tW := template.New("with template")
	tW = template.Must(tW.Parse("不爲空的 pipeline if demo: {{if `anything`}} 我有內容,我會輸出. {{end}}\n"))
	tW.Execute(os.Stdout,nil)

	tElse := template.New("else template")
	tElse = template.Must(tElse.Parse("if-else demo: {{if `anything`}} if部分 {{else}} else部分.{{end}}\n"))
	tElse.Execute(os.Stdout,nil)
}

/*
模板變量
有時候,我們在模板使用過程中需要定義一些局部變量,我們可以在一些操作中申明局部變量,例如with``range``if過程中申明局部變量,這個變量的作用域是{{end}}之前,Go語言通過申明的局部變量格式如下所示:
*/
func testtemplatevar(){
	tVar := template.New("var template")
	//{{"output" | printf "%q"}}
	//豎線 |  左邊的結果output 作爲printf 函數最後一個參數。(等同於:printf("%q", "output")。)
	tVar = template.Must(tVar.Parse(`
{{with $x := "output" | printf "%s"}}{{$x}}{{end}}
{{with $x := "output"}}{{printf "%v" $x}}{{end}}
{{with $x := "output"}}{{$x | printf "%q"}}{{end}}
`))
	tVar.Execute(os.Stdout,nil)
}

 

參考:https://www.golang123.com/books/9/chapters/181

 

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