engine.LoadHTMLGlob(加载特定目录)
只有一个参数,通配符,如:template/* 意思是找当前项目路径下 template 文件夹下所有的html 文件,如:engine.LoadHTMLGlob("templates/*")
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/index.tmpl
<html><h1>{{ .title }}</h1></html>
使用不同目录下名称相同的模板
func main() {router := gin.Default()router.LoadHTMLGlob("templates/**/*")router.GET("/posts/index", func(c *gin.Context) {c.HTML(http.StatusOK, "posts/index.tmpl", gin.H{"title": "Posts",})})router.GET("/users/index", func(c *gin.Context) {c.HTML(http.StatusOK, "users/index.tmpl", gin.H{"title": "Users",})})router.Run(":8080")}
templates/posts/index.tmpl
{{ define "posts/index.tmpl" }}<html><h1>{{ .title }}</h1><p>Using posts/index.tmpl</p></html>{{ end }}
自定义模板渲染器
你可以使用自定义的 html 模板渲染
import "html/template"func main() {router := gin.Default()html := template.Must(template.ParseFiles("file1", "file2"))router.SetHTMLTemplate(html)router.Run(":8080")}
自定义分隔符
你可以使用自定义分隔
r := gin.Default()r.Delims("{[{", "}]}")r.LoadHTMLGlob("/path/to/templates")
自定义模板功能
查看详细示例代码。
main.go
import ("fmt""html/template""net/http""time""github.com/gin-gonic/gin")func formatAsDate(t time.Time) string {year, month, day := t.Date()return fmt.Sprintf("%d/%02d/%02d", year, month, day)}func main() {router := gin.Default()router.Delims("{[{", "}]}")router.SetFuncMap(template.FuncMap{"formatAsDate": formatAsDate,})router.LoadHTMLFiles("./testdata/template/raw.tmpl")router.GET("/raw", func(c *gin.Context) {c.HTML(http.StatusOK, "raw.tmpl", map[string]interface{}{"now": time.Date(2017, 07, 01, 0, 0, 0, 0, time.UTC),})})router.Run(":8080")}
raw.tmpl
Date: {[{.now | formatAsDate}]}
结果:
Date: 2017/07/01
engine.LoadHTMLFiles(特定文件)
不定长参数,可以传多个字符串,使用这个方法需要指定所有要使用的html文件路径
,如:engine.LoadHTMLFiles("templates/index.html","template/user.html")
指定模板路径
// 使用*gin.Context下的HTML方法func Hello(context *gin.Context) {name := "zhiliao"context.HTML(http.StatusOK,"index.html",name)}
注意:不要使用 golang 里面 run,否则会报错
panic: html/template: pattern matches no files: 'templates/*'
在 cmd 运行即可
多级目录的模板指定
如果有多级目录,比如 templates 下有user 和 article 两个目录,如果要使用里面的 html 文件,必须得在 Load 的时候指定多级才可以,比如:engine.LoadHTMLGlob("templates/**/*")
有几级目录,得在通配符上指明
- 两级:
engine.LoadHTMLGlob("templates/**/*") - 三级:
engine.LoadHTMLGlob("templates/**/**/*") 
- 两级:
 指定html文件
// 除了第一级的 templates 路径不需要指定,后面的路径都要指定
e.g.:context.HTML(http.StatusOK,"user/index.html","zhiliao")
- 在html中 ```html 必须使用
 
{{ define “user/index.html” }}
html内容
参考链接
原文
原文作者:Go 技术论坛文档:《Gin 框架中文文档(1.5)》 转自链接:https://learnku.com/docs/gin-gonic/2019/examples-html-rendering/6160 版权声明:著作权归作者所有。商业转载请联系作者获得授权,非商业转载请保留以上作者信息和原文链接。
