Gin HTML渲染

我们首先创建一个存放模板文件的templates文件夹,然后在其内部写入一个index.html,代码如下

<!DOCTYPE html>
<html lang="en">
<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>
<body>
    <h1>
        账号是:{{.name}}
    </h1>
    <h1>
        密码是:{{.pwd}}
    </h1>
</body>
</html>

在Gin框架中使用​LoadHTMLGlob()​ 或者 ​LoadHTMLFiles()​来渲染HTML模板

package main

import (
	"net/http"
	"github.com/gin-gonic/gin"
)

func main() {
	r := gin.Default()
	r.LoadHTMLGlob("./templates/*")
	r.GET("/demo",func(c *gin.Context) {
		c.HTML(http.StatusOK,"index.html",gin.H{
			"name":"admin",
			"pwd":"123456",
		})
	})
	r.Run()
}

运行上述代码,并在浏览器中访问127.0.0.1:8080/demo

Gin加载HTML