一.调用方法
- 在模版中调用函数时,如果是无参函数直接调用函数名即可,没有函数的括号
- 例如在go源码中
时间变量.Year()
在模版中{{时间.Year}}
- 在模版中调用有参函数时参数和函数名称之间有空格,参数和参数之间也是空格
- 给定go文件代码
package main
import (
"net/http"
"html/template"
"time"
)
func welcome(w http.ResponseWriter, r *http.Request) {
t, _ := template.ParseFiles("view/index.html")
time:=time.Date(2018,1,2,3,4,5,0,time.Local)
t.Execute(w, time)
}
func main() {
server := http.Server{Addr: ":8090"}
http.HandleFunc("/", welcome)
server.ListenAndServe()
}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Title</title>
</head>
<body>
<pre>
取出时间中的年:{{.Year}} <br/>
取出时间中的年:{{.Month}} <br/>
格式化后的内容:{{.Format "2006-01-02"}}
</pre>
</body>
</html>
二.调用自定义函数/方法
- 如果希望调用自定义函数,需要借助html/template包下的FuncMap进行映射
- FuncMap本质就是map的别名
type FuncMap map[string]interface{}
- 函数被添加映射后,只能通过函数在FuncMap中的key调用函数
- go文件代码示例
package main
import (
"net/http"
"html/template"
"time"
)
func MyFormat(s string) string{
t,_:=time.Parse("2006-01-02 15:04:05",s)
t=t.Add(60e9)
return t.Format("2006-01-02 15:04:05")
}
func html(res http.ResponseWriter, req *http.Request) {
funcMap:=template.FuncMap{"mf":MyFormat}
t:=template.New("demo.html").Funcs(funcMap)
t, _ = t.ParseFiles("demo.html")
s:="2009-08-07 01:02:03"
t.Execute(res, s)
}
func main() {
server := http.Server{
Addr: "localhost:8090",
}
http.HandleFunc("/html", html)
server.ListenAndServe()
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
传递过来的时间:{{.}}<br/>
调用自定义函数,格式化后的时间:{{mf .}}<br/>
</body>
</html>