Skip to content

使用模板渲染

单目录

创建模板文件目录,比如在项目根目录的 templates 目录下。

然后需要在启动应用的时候加载目录文件,如下:

html
func main() { r := gin.Default() r.LoadHTMLGlob("templates/*") // ...
r.Run(":8080") }

然后在方法中即可使用模板文件,如下:

html
c.HTML(http.StatusOK, "index.tmpl", nil)

其中第三个参数是模板参数

多级目录

yaml
func main() {
	r := gin.Default()
	r.Static("/static", "./static")
  # 二级目录
	r.LoadHTMLGlob("templates/**/*")
  # 三级目录
  r.LoadHTMLGlob("templates/**/**/*")
   // ...
	r.Run(":8080")
}

渲染的时候需要:

html
c.HTML(http.StatusOK, "index/index.tmpl", nil)

并且在 index.tmpl 中还需要:

html
{{ define "index/index.templ" }}
<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <title>修改模板引擎的标识符</title>
  </head>
  <body>
    <div>{{ . | safe }}</div>
  </body>
</html>
{{ end }}
最近更新