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("/with", func(c *gin.Context) { a:= &Article{ Title:"新闻标题", Content:"新闻内容", } c.HTML(http.StatusOK,"web/with.html",gin.H{ "title":"新闻页面", "news":a, }) }) r.Run() }
web/with.html
<!-- 相当于给模板定义一个名称 define 和 end 是成对出现的 --> {{ define "web/with.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> <!-- with 解构结构体 --> <p>{{.news.Title}}</p> <p>{{.news.Content}}</p> {{with .news}} {{.Title}} {{.Content}} {{end}} </bady> </html> {{ end }}