golang 模板template自定义函数用法示例以及注意事项

package main

import (
	"html/template"
	"net/http"
	"time"
)

type User struct {
	Username, Password string
	RegTime            time.Time
}

//这个函数的名字要大写,要不然模板中无法调用这个函数
func ShowTime(t time.Time, format string) string {
	return t.Format(format)
}

func main() {
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
                //这边有个地方值得注意,template.New()函数中参数名字要和ParseFiles()
                //函数的文件名要相同,要不然就会报错:"" is an incomplete template
		tmpl := template.New("demo.html")
		tmpl = tmpl.Funcs(template.FuncMap{"showtime": ShowTime})
		tmpl, _ = tmpl.ParseFiles("demo.html")
		//mpl, _ = tmpl.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>
		//`)
		// tmpl = template.Must(tmpl.ParseFiles("templates/demo.html"))  // 这样写也可以的,那么这个template.Must到底干嘛的呢? 其实就是省略了一个err
		user := User{"dotcoo", "dotcoopwd", time.Now()}
		if err := tmpl.ExecuteTemplate(w, "demo.html", user); nil != err {
			http.Error(w, err.Error(), http.StatusBadRequest)
		}
	})
	http.ListenAndServe(":8082", nil)
}
<h1>Func</h1>
<p>{{.Username}}|{{.Password}}|{{.RegTime.Format "2006-01-02 15:04:05"}}</p>
<p>{{.Username}}|{{.Password}}|{{showtime .RegTime "2006-01-02 15:04:05"}}</p>

最终显示结果:

 

 

 

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值