main.go文件
package main import( "github.com/gin-gonic/gin" "net/http" ) type Article struct { Title string Content string } func main() { r := gin.Default() //r.LoadHTMLFiles() //多个框架是加/**/代表目录 r.LoadHTMLGlob("view/**/*") //前端 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", }, }, }) }) 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("/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 {{.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}}
{{else}}- 切片中无数据
{{end}}
{{ end }} web/news.html
{{ define "web/news.html" }}document {{ end }} WEB
{{.title}}
{{.news.Title}}
{{.news.Content}}
admin/index.html
{{ define "admin/index.html" }}document {{ end }} {{.title}}