Go语言在模版中调用函数

一.调用方法

  • 在模版中调用函数时,如果是无参函数直接调用函数名即可,没有函数的括号
  • 例如在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()
}

  • 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文件代码示例
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代码示例
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    传递过来的时间:{{.}}<br/>
    调用自定义函数,格式化后的时间:{{mf .}}<br/>
</body>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

书香水墨

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值