一.调用方法
- 在模版中调用函数时,如果是无参函数直接调用函数名即可,没有函数的括号
- 例如在go源码中
时间变量.Year()在模版中{{时间.Year}} - 在模版中调用有参函数时参数和函数名称之间有空格,参数和参数之间也是空格
- 给定go文件代码 ```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() }
- html代码如下```html<!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><!--调用time变量的无参方法-->取出时间中的年:{{.Year}} <br/>取出时间中的年:{{.Month}} <br/><!--调用有参数方法-->格式化后的内容:{{.Format "2006-01-02"}}</pre></body></html>
二.调用自定义函数/方法
- 如果希望调用自定义函数,需要借助html/template包下的FuncMap进行映射
- FuncMap本质就是map的别名
type FuncMap map[string]interface{} - 函数被添加映射后,只能通过函数在FuncMap中的key调用函数
- go文件代码示例 ```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)//在时间上添加1分钟 return t.Format(“2006-01-02 15:04:05”) }
func html(res http.ResponseWriter, req *http.Request) { //把自定义函数绑定到FuncMap上 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() }
- HTML代码示例```html<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Title</title></head><body>传递过来的时间:{{.}}<br/>调用自定义函数,格式化后的时间:{{mf .}}<br/></body></html>
