main.go
package main
import (
"github.com/gin-gonic/gin"
"html/template"
"net/http"
"time"
)
func main() {
app := gin.Default()
/*Gin模板中,增加自定义函数*/
app.SetFuncMap(template.FuncMap{
/*format_time就是在模板中的名字
formatTime是处理函数*/
"format_time":formatTime,
})
/*渲染单个html文件*/
app.LoadHTMLFiles("index.html")
app.GET("/index",index)
_ = app.Run("127.0.0.1:80")
}
func index(c *gin.Context) {
/*
设置相应状态码为http.StatusOK
使用模板"index.html"
传入模板的参数为time.Now()
*/
c.HTML(http.StatusOK,"index.html",time.Now())
}
func formatTime(str interface{}) template.HTML {
/* 将传入的空接口类型的str变量,使用类型断言进行转换为time.Time
然后使用Format("2006-01-02 15:04:05")方法进行格式化输出*/
format := str.(time.Time).Format("2006-01-02 15:04:05")
/*
将格式化后的内容加载到模板中,并返回template.HTML类型
*/
return template.HTML(format)
}
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>
index.html
</h1>
<h3>
{{/*原样输出传递进来的变量*/}}
{{.}}
</h3>
<h3>
{{/*将传递进来的变量以参数的形式传入到format_time函数中,获取格式化后的日期时间*/}}
{{format_time .}}
</h3>
</body>
</html>
本文暂时没有评论,来添加一个吧(●'◡'●)