代码:

package main

import (
    "bytes"
    "fmt"
    "text/template"
    "time"
)

func FormatNow(format string) string {
    return time.Now().Format(format)
}

func main() {
    tmpl := template.New("t1")                                  // 模版名字
    tmpl = tmpl.Funcs(template.FuncMap{"formatNow": FormatNow}) // 模版使用的函数

    tmpl, err := tmpl.Parse("hello, {{.}} {{formatNow \"2006-01-02\"}}") // 模版
    if err != nil {
        panic(err)
    }

    var doc bytes.Buffer
    name := "ghj1976"
    err = tmpl.Execute(&doc, name)
    if err != nil {
        panic(err)
    }
    fmt.Println(doc.String())

    fmt.Println(FormatNow("2006-01-02"))
}

执行结果:

go 使用模板函数的例子

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-12-22
  • 2022-12-23
  • 2022-12-23
  • 2021-11-19
猜你喜欢
  • 2021-04-19
  • 2021-08-15
  • 2022-12-23
  • 2022-02-10
  • 2021-06-25
  • 2021-07-20
相关资源
相似解决方案