html/template 基礎語法


文檔地址: https://godoc.org/html/template

創建一個模板

var t *template.Template
t, _ = t.Parse(``)

輸出

`{{ . }}` 輸出

調用結構的方法

`{{ .Say "hello }}`

模板中定義變量

`{{ $a := "模板中的變量" }}`

模板函數

t.Funcs(template.FuncMap{"test1": test1}) 注冊函數
t.Funcs(template.FuncMap{"test2": test2});

{{ 函數名 }} 輸出函數返回值
{{ 函數名 參數1 參數2 }}

{{ .字段	名 | 函數名 }} 以字段的值作為函數的參數

t.Parse(`{{test1}}
	{{ test2 "參數" }})
	{{.UserName | test2 }}
	`)
t.Execute(os.Stdout, Person{})

條件判斷

{{ if 1 }} true  {{ else }} {{ end }}

遍歷

{{ range $k, &v := .Map }}
	{{ $k }} {{ $v }}
{{ end }}

嵌套模板

{{ define "tp1" }} I'm template 1 {{ end }}
{{ define "tp2" }} I'm template 2 {{ . }} {{ end }}
{{ define "tp3" }} {{ template "tp1"}} {{ template "tp2" }} {{ end }}
{{ template "tp1" }}
{{ template "tp2" "test1" }}

{{ template "tp3" "test1" }}

內置的模板函數

{{ and 3 4 }} //如果3為真, 返回4, 否則返回3

{{ or 3 4 }} // 如果3位真, 返回3, 否則返回4

{{ call sum 1 3 5 7 }} // call 后的第一個參數的返回值必須是一個函數

{{ "<br>"|html}} // 轉義文本中html的標簽

{{index .Contact "qq"}} // 返回 Contact 索引為qq的值

{{ "?a=123&b="你好"|js}} //	返回用js的escape處理后的文本, 自動進行html轉義

{{"hello"|len}} // 返回參數的長度

{{ not 0 }} // bool 取反

{{"你好"|print "世界"}} // fmt.Sprint 的別名

{{"你好"|printf "%d %s" 123}} // Spintf的別名

{{"你好"|println "世界"}} // Println

{{?q=關鍵字&p=1|urlquery}} // 進行url編碼

{{ if eq 1 1}} 等於
	- eq 等於
	- ne 不等於
	- lt 
	- le 
	- gt
	- ge


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM