HTML模板渲染
gin支持加载HTML模板, 然后根据模板参数进行配置并返回相应的数据。
先要使用 LoadHTMLGlob() 或者 LoadHTMLFiles()方法来加载模板文件,新建一个go文件(demo11_html.go):func main() {
router := gin.Default() //加载模板
router.LoadHTMLGlob("templates/*") //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")
}
创建一个目录:templates,然后在该目录下创建一个模板文件:
templates/index.tmpl{{ .title }}