这篇文章主要介绍了golang模板template自定义函数用法,结合实例形式分析了Go语言模板自定义函数的基本定义与使用方法,需要的朋友可以参考下
本文实例讲述了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语言程序设计有所帮助。
您可能感兴趣的文章:
- Go html/template 模板的使用实例详解
- 详解golang 模板(template)的常用基本语法
- Go Web 编程中的模板库应用指南(超详细)
- goland 设置注释模板的过程图文详解
- Go语言基础模板设计模式示例详解
- Go模板template用法详解
- 深入解析Go template模板使用详解