Golang Gin使用模板及框架下返回Json
阿新 • • 發佈:2020-07-25
./view/user/user 裡面的繼承了 ./view/template/master模板
./view/template/master模板 程式碼
<!DOCTYPE html> <html> <head> </head> <body> <p>模板上面內容</p> {{block "context" .}}{{end}} <p>模板下面內容</p> {{ say "<div style=\"background-color:red;\">你好</div>" }} </body> </html>
./view/user/user程式碼
{{template "master" .}} {{define "context"}} {{"<div style=\"background-color:red;\">你好</div>" |say}} {{.title}} <p>user內容</p> {{end}}
main() 裡面的後臺程式碼,注意:
engin.SetFuncMap(template.FuncMap{"say":say,})
engin.LoadHTMLFiles("./view/template/master", "./view/user/user")
package main import ( "github.com/gin-gonic/gin" "html/template" "net/http" ) // 通過該方法可以將內容以HTML的形式輸出 func say(s string) template.HTML { return template.HTML(s) } func main(){ engin :=gin.Default() engin.GET("/user", func(c *gin.Context) { // 設定 FuncMap 即前端可以呼叫的方法engin.SetFuncMap(template.FuncMap{"say":say,}) // 解析模板 engin.LoadHTMLFiles("./view/template/master", "./view/user/user") // 渲染模板 c.HTML(http.StatusOK,"user",gin.H{"title":"中間內容",}) }) engin.GET("/ouser", func(c *gin.Context) { engin.LoadHTMLFiles("./view/myuser/user") c.HTML(http.StatusOK,"user",gin.H{"title":"你好另一個User",}) }) engin.Run() }
關於Gin框架返回Json的例項
package main import ( "github.com/gin-gonic/gin" "html/template" "net/http" ) type User struct { UserId string UserName string } func main(){ engin :=gin.Default() engin.GET("/userinfo", func(c *gin.Context) { user :=&User{UserId: "1",UserName: "張三"}
// Gin 會自動將User轉換成JSon返回給前端,其他像Map,slice也一樣 c.JSON(http.StatusOK,user) }) engin.Run() }