golang template template custom function usage example
- 2020-06-01 09:59:08
- OfStack
This example demonstrates the use of the golang template template custom functions. I will share it with you for your reference as follows:
golang's templates are 10 points strong, and unix pipe-style function calls are a favorite.
There are many built-in templates that you can refer to in the pkg documentation,
You can also implement custom functions.
Examples are as follows:
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)
}
I hope this article has been helpful to you in the programming of Go language.