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 和 end 是成对出现的 --> {{ define "web/index.html" }} <!DOCTYPE html> <html lang="cn"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=Edge"> <meta name="viewport" content="width=device-width,initial-scale=1.0"> <title>document</title> </head> <bady> <h2>{{.title}}</h2> {{$t := .title}} <h4>{{$t}}</h4> <!-- 条件判断 eq:等于、ne:不等于、lt小于、le小于等于、gt:大于、ge:大于等于 --> {{if ge .sort 60}} <h5>及格</h5> {{else}} <h5>不及格</h5> {{end}} <!-- 循环遍历数据 切片 --> {{range $key,$value := .list}} <li>key=>{{$key}}-----value=>{{$value}}</li> {{end}} <br/> <!-- 循环遍历数据 切片接口--> {{range $key,$value := .newlist}} <li>key=>{{$key}}-----value.Title=>{{$value.Title}}-------value.Content=>{{$value.Content}}</li> {{else}} <li>切片中无数据</li> {{end}}
</bady> </html> {{ end }} web/news.html
<!-- 相当于给模板定义一个名称 define 和 end 是成对出现的 --> {{ define "web/news.html" }} <!DOCTYPE html> <html lang="cn"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=Edge"> <meta name="viewport" content="width=device-width,initial-scale=1.0"> <title>document</title> </head> <bady> <h5>WEB</h5> <h2>{{.title}}</h2> <br> {{.news.Title}} <br> {{.news.Content}} </bady> </html> {{ end }}
admin/index.html
<!-- 相当于给模板定义一个名称 define 和 end 是成对出现的 --> {{ define "admin/index.html" }} <!DOCTYPE html> <html lang="cn"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=Edge"> <meta name="viewport" content="width=device-width,initial-scale=1.0"> <title>document</title> </head> <bady> <h2>{{.title}}</h2> </bady> </html> {{ end }}