Gin 使用示例(十六):HTML 视图模板渲染
由 学院君 创建于9个月前, 最后更新于 9个月前
版本号 #1
1952 views
0 likes
0 collects
在 Gin 框架中,可以使用 LoadHTMLGlob() 或 LoadHTMLFiles() 来渲染 HTML。
单目录
如果要加载的 HTML 文件位于同一个目录下,示例代码如下(src/gin-demo/examples/html.go):
func main() {
router := gin.Default()
router.LoadHTMLGlob("templates/*.tmpl")
// 如果使用 LoadHTMLFiles 的话这么做(需要列举所有需要加载的文件,不如上述 LoadHTMLGlob 模式匹配方便):
// router.LoadHTMLFiles("templates/template1.html", "templates/template2.html")
router.GET("/index", func(c *gin.Context) {
c.HTML(http.StatusOK, "index.tmpl", gin.H{
"title": "Main website",
})
})
router.Run(":8080")
}
对应的视图模板(src/gin-demo/examples/templates/index.tmpl):