golang的模板十分强大,其中的unix管道风格函数调用很是喜欢.
另外还可以实现自定义函数.
package main
import (
"text/template"
"time"
"os"
)
type User struct {
Username, Pass
word 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)
}