首先奉上我的项目目录结构
main.go
package main import ( "fmt" "github.com/gin-gonic/gin" "html/template" "net/http" "time" ) type Article struct { Title string Content string } func UnixToTime(timestamp int) string { fmt.Println(timestamp) t :=time.Unix(int64(timestamp),0) return t.Format("2006-01-02 15:04:05") } func Println(str1 string,str2 string) string{ //fmt.Println(str1,str2) return str1+"---------"+str2 } func main() { r := gin.Default() //r.LoadHTMLFiles() //自定义模板函数 注意要办这个函数放在加载模板前 r.SetFuncMap(template.FuncMap{ "UnixToTime":UnixToTime, "prt":Println, }) //加载模板放在配置路由上面 r.LoadHTMLGlob("view/**/*") //配置加载静态文件目录 r.Static("/static","./static") //前端 r.GET("/", func(c *gin.Context) { c.HTML(http.StatusOK,"web/index.html",gin.H{ "title":"首页sss", "sort" : 55, "list" : []string{"我是谁","我是我","我是人","我是个好人你信吗?"}, "newlist":[]interface{}{ &Article{ Title:"新闻标题1", Content:"新闻内容1", }, &Article{ Title:"新闻标题2", Content:"新闻内容2", }, }, "date" :1660274555, }) }) r.GET("/news", func(c *gin.Context) { a:= &Article{ Title:"新闻标题", Content:"新闻内容", } c.HTML(http.StatusOK,"web/news.html",gin.H{ "title":"新闻页面", "news":a, }) }) r.GET("/with", func(c *gin.Context) { a:= &Article{ Title:"新闻标题", Content:"新闻内容", } c.HTML(http.StatusOK,"web/with.html",gin.H{ "title":"新闻页面", "news":a, }) }) //后端 r.GET("/admin", func(c *gin.Context) { c.HTML(http.StatusOK,"admin/index.html",gin.H{ "title":"首页sss", }) }) r.GET("/admin/news", func(c *gin.Context) { a:= &Article{ Title:"新闻标题", Content:"新闻内容", } c.HTML(http.StatusOK,"admin/news.html",gin.H{ "title":"新闻页面", "news":a, }) }) r.Run() }
web/index.html
{{ define "web/index.html" }}document {{template "public/page_header.html" .}} {{ end }}{{.title}}
{{$t := .title}}{{$t}}
{{if ge .sort 60}}及格
{{else}}不及格
{{end}} {{range $key,$value := .list}}key=>{{$key}}-----value=>{{$value}} {{end}}
{{range $key,$value := .newlist}}key=>{{$key}}-----value.Title=>{{$value.Title}}-------value.Content=>{{$value.Content}} {{end}}
{{len .title}}原样输出:{{.date}} 自定义函数输出:{{UnixToTime .date}} 自定义函数prt输出:{{prt .title .title}} {{template "public/page_footer.html" .}}
public/page_footer.html
{{ define "public/page_footer.html" }}我是一个公共的底部
{{ end }}
public/page_header.html
{{ define "public/page_header.html" }}我是一个公共的标题
{{ end }}
效果图: