golang模板template自定义函数 golang模板template自定义函数用法示例

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

golang模板template自定义函数 golang模板template自定义函数用法示例

dotcoo   2021-03-22 我要评论
想了解golang模板template自定义函数用法示例的相关内容吗,dotcoo在本文为您仔细讲解golang模板template自定义函数的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:golang,模板,template,自定义函数,下面大家一起来学习吧。

本文实例讲述了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语言程序设计有所帮助。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们