golang模板template自定义函数用法示例
本文实例讲述了golang模板template自定义函数用法。分享给大家供大家参考,具体如下:
golang的模板十分强大,其中的unix管道风格函数调用很是喜欢.
模板中有很多内置可以参看pkg文档,
另外还可以实现自定义函数.
例子如下:
packagemain
import(
"text/template"
"time"
"os"
)
typeUserstruct{
Username,Passwordstring
RegTimetime.Time
}
funcShowTime(ttime.Time,formatstring)string{
returnt.Format(format)
}
funcmain(){
u:=User{"dotcoo","dotcoopwd",time.Now()}
t,err:=template.New("text").Funcs(template.FuncMap{"showtime":ShowTime}).
Parse(`<p>{{.Username}}|{{.Password}}|{{.RegTime.Format"2006-01-0215:04:05"}}</p>
<p>{{.Username}}|{{.Password}}|{{showtime.RegTime"2006-01-0215:04:05"}}</p>
`)
iferr!=nil{
panic(err)
}
t.Execute(os.Stdout,u)
}
希望本文所述对大家Go语言程序设计有所帮助。
热门推荐
10 除夕祝福语简短创意牛年
11 女士四十岁祝福语简短
12 春节初二祝福语简短
13 高考加油祝福语简短押韵
14 妈妈生病康复祝福语简短
15 厨房祝福语简短100句
16 晚安好梦祝福语简短
17 疫情对妈妈祝福语简短
18 爸妈对宝宝祝福语简短