1.进行HTML页面渲染
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
router := gin.Default()
router.LoadHTMLGlob("templates/*") //会加载templates目录下所有的html文件
router.GET("/index", func(c *gin.Context) {
c.HTML(http.StatusOK, "index.html", nil)//index.html为templates目录下的文件
})
router.Run(":80")
}
1)templates/index.html模板
<h1>Welcome to the Index Page!</h1>
<h2>{{.Title}}</h2>
<h2>{{.Name}}</h2>
<h2>{{.Email}}</h2>
2)给html模板传参数
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
router := gin.Default()
router.LoadHTMLGlob("templates/*") //会加载templates目录下所有的html文件
data := map[string]string{
"Title": "index-page",
"Name": "memories",
"Email": "123456@qq.com",
}
router.GET("/index", func(c *gin.Context) {
c.HTML(http.StatusOK, "index.html", data) //该函数的第三个参数就是 要给html模板传递的信息
})
router.Run(":80")
}
要传递的信息data不仅可以使map类型,还可以是struct、JSON等等类型
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
router := gin.Default()
router.LoadHTMLGlob("templates/*") //会加载templates目录下所有的html文件
router.GET("/index", func(c *gin.Context) {
c.HTML(http.StatusOK, "index.html", gin.H{
"Title": "index-page",
"Name": "memories",
"Email": "123456@qq.com",
}) //gin.H类型的信息
})
router.Run(":80")
}
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
router := gin.Default()
router.LoadHTMLGlob("templates/*") //会加载templates目录下所有的html文件
data := &struct {
Title string //注意:这里的字段的首字母必须要大写,这是go语言字段访问权限的部分的知识
Name string
Email string
}{
Title: "index-page",
Name: "memories",
Email: "123456@qq.com",
}
router.GET("/index", func(c *gin.Context) {
c.HTML(http.StatusOK, "index.html", data) //struct类型的信息
})
router.Run(":80")
}
3)加载html模板的函数
(1)router.LoadHTMLGlob("templates/*")
这个函数可以使用通配符,即*、?
和 []
。
* :匹配任意长度的字符串 e.g: h*.html 即以h开头 .html结尾的所有文件
?:匹配单个任意字符 额 e.h: hell?.html 即格式为hell_.html的所有文件
[] : 匹配指定范围的字符 e.g: file[1-3].html 即file.html或file2.html或file3.html
(2)router.LoadHTMLFiles
这个函数不可以使用通配符,必须指定清楚要加载的文件名
e.g: router.LoadHTMLFiles("templates/index.html")