本文實例講述了golang模板template自定義函數用法。分享給大家供大家參考,具體如下:
golang的模板十分強大,其中的unix管道風格函數調用很是喜歡.
模板中有很多內置可以參看pkg文檔,
另外還可以實現自定義函數.
例子如下:
復制代碼 代碼如下:
package main
import (
"text/template"
"time"
"os"
)
type User struct {
Username, Password string
RegTime time.Time
}
func ShowTime(t time.Time, format string) string {
return t.Format(format)
}
func main() {
u := User{"dotcoo", "dotcoopwd", time.Now()}
t, err := template.New("text").Funcs(template.FuncMap{"showtime":ShowTime}).
Parse(`p>{{.Username}}|{{.Password}}|{{.RegTime.Format "2006-01-02 15:04:05"}}/p>
p>{{.Username}}|{{.Password}}|{{showtime .RegTime "2006-01-02 15:04:05"}}/p>
`)
if err != nil {
panic(err)
}
t.Execute(os.Stdout, u)
}
希望本文所述對大家Go語言程序設計有所幫助。
您可能感興趣的文章:- Golang中文字符串截取函數實現原理
- golang中strconv.ParseInt函數用法示例
- Golang的os標準庫中常用函數的整理介紹
- Golang記錄、計算函數執行耗時、運行時間的一個簡單方法
- 秒懂Golang匿名函數