您现在的位置是:网站首页> 编程资料编程资料
golang模板template自定义函数用法示例_Golang_
2023-05-26
439人已围观
简介 golang模板template自定义函数用法示例_Golang_
本文实例讲述了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(`
`)
if err != nil {
panic(err)
}
t.Execute(os.Stdout, u)
}
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(`
{{.Username}}|{{.Password}}|{{.RegTime.Format "2006-01-02 15:04:05"}}
{{.Username}}|{{.Password}}|{{showtime .RegTime "2006-01-02 15:04:05"}}
`)
if err != nil {
panic(err)
}
t.Execute(os.Stdout, u)
}
希望本文所述对大家Go语言程序设计有所帮助。
您可能感兴趣的文章:
相关内容
- golang实现http服务器处理静态文件示例_Golang_
- golang简单位运算示例_Golang_
- golang解析xml的方法_Golang_
- golang简单获取上传文件大小的实现代码_Golang_
- golang实现简单的udp协议服务端与客户端示例_Golang_
- golang的HTTP基本认证机制实例详解_Golang_
- golang简单tls协议用法完整示例_Golang_
- golang网络socket粘包问题的解决方法_Golang_
- golang判断chan channel是否关闭的方法_Golang_
- golang实现unicode转换为字符串string的方法_Golang_
