使用模板渲染
# 单目录
创建模板文件目录,比如在项目根目录的 templates 目录下。
然后需要在启动应用的时候加载目录文件,如下:
func main() { r := gin.Default() r.LoadHTMLGlob("templates/*") // ...
r.Run(":8080") }
1
2
2
然后在方法中即可使用模板文件,如下:
c.HTML(http.StatusOK, "index.tmpl", nil)
1
其中第三个参数是模板参数
# 多级目录
func main() {
r := gin.Default()
r.Static("/static", "./static")
# 二级目录
r.LoadHTMLGlob("templates/**/*")
# 三级目录
r.LoadHTMLGlob("templates/**/**/*")
// ...
r.Run(":8080")
}
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
渲染的时候需要:
c.HTML(http.StatusOK, "index/index.tmpl", nil)
1
并且在 index.tmpl 中还需要:
{{ define "index/index.templ" }}
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<title>修改模板引擎的标识符</title>
</head>
<body>
<div>{{ . | safe }}</div>
</body>
</html>
{{ end }}
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
作者:
本文链接:https://jokerbai.com
版权声明:本博客所有文章除特别声明外,均采用 署名-非商业性-相同方式共享 4.0 国际 (CC-BY-NC-SA-4.0) 许可协议。转载请注明出处!
上次更新: 2025/07/19, 09:17:41
- 02
- 使用Zadig从0到1实现持续交付平台07-19
- 03
- 基于Jira的运维发布平台07-19