Gin c.HTML 完整教程

c.HTML() 是 Gin 渲染 HTML 模板 的核心方法,必须配合 LoadHTMLGlob/LoadHTMLFiles 使用,专门用来把后端数据注入到 HTML 页面。

一、核心语法

go 复制代码
c.HTML(httpCode int, tmplName string, data any)
  • httpCode:状态码,一般填 200
  • tmplName模板文件名(不是路径!)
  • data:传给模板的数据,常用 gin.H{} 字典

二、完整最小示例

1. 目录结构

复制代码
project/
├── main.go
└── templates/
    └── index.html

2. main.go

go 复制代码
package main

import (
	"github.com/gin-gonic/gin"
	"net/http"
)

func main() {
	r := gin.Default()

	// 1. 加载所有HTML模板(必须写在c.HTML之前)
	r.LoadHTMLGlob("templates/*")

	// 2. 路由渲染页面
	r.GET("/", func(c *gin.Context) {
		// 渲染 index.html,传数据
		c.HTML(http.StatusOK, "index.html", gin.H{
			"Title": "Gin c.HTML教程",
			"Msg":   "后端传过来的消息",
			"Num":   666,
		})
	})

	r.Run(":8080")
}

3. templates/index.html

html 复制代码
<!DOCTYPE html>
<html>
<head>
    <title>{{.Title}}</title>
</head>
<body>
    <h1>{{.Msg}}</h1>
    <p>数字:{{.Num}}</p>
</body>
</html>

运行访问 http://localhost:8080,数据就渲染出来了。


三、关键知识点

1. LoadHTMLGlob 路径规则

  • templates/*:只加载一级目录
  • templates/**/*:加载所有子目录(推荐)
go 复制代码
r.LoadHTMLGlob("templates/**/*")

2. 子目录模板怎么渲染?

目录:

复制代码
templates/
    index.html
    admin/
        dash.html

渲染:

go 复制代码
c.HTML(200, "admin/dash.html", gin.H{})

3. 数据传递高级用法

传切片/数组

go 复制代码
c.HTML(200, "index.html", gin.H{
	"List": []string{"苹果", "香蕉", "橙子"},
})

html 循环:

html 复制代码
{{range .List}}
    <li>{{.}}</li>
{{end}}

传结构体

go 复制代码
type User struct {
	Name string
	Age  int
}

c.HTML(200, "index.html", gin.H{
	"User": User{"张三", 20},
})

html:

html 复制代码
<p>姓名:{{.User.Name}}</p>
<p>年龄:{{.User.Age}}</p>

四、模板继承(layout 布局,重点)

实际项目都用母版页,避免每个页面重复写 html/head/body。

目录

复制代码
templates/
    layout.html   # 母版
    home.html     # 子页面

layout.html

html 复制代码
<!DOCTYPE html>
<html>
<head>
    <title>{{.Title}}</title>
</head>
<body>
    <header>公共头部</header>
    {{template "content" .}}  <!-- 子页面占位 -->
    <footer>公共底部</footer>
</body>
</html>

home.html

html 复制代码
{{define "content"}}
    <h1>我是首页内容</h1>
    <p>{{.Msg}}</p>
{{end}}

main.go

go 复制代码
r.LoadHTMLGlob("templates/*")

r.GET("/home", func(c *gin.Context) {
	c.HTML(200, "layout.html", gin.H{
		"Title": "首页",
		"Msg":   "hello gin",
	})
})

五、静态资源搭配(CSS/JS/图片)

c.HTML 只管页面渲染,静态文件必须用 r.Static

go 复制代码
// 托管静态资源
r.Static("/static", "./static")

html 中使用:

html 复制代码
<link rel="stylesheet" href="/static/css/style.css">
<script src="/static/js/main.js"></script>

六、常见错误&避坑

  1. 找不到模板
    原因:LoadHTMLGlob 路径不对,必须相对运行命令的目录
  2. 子页面渲染不出来
    r.LoadHTMLGlob("templates/**/*")
  3. 变量不显示
    模板语法是 {``{.变量名}}不能少点
  4. 纯静态html
    不用 c.HTML,直接用 r.Static

七、一句话总结

  • LoadHTMLGlob:加载模板文件
  • c.HTML:渲染模板 + 注入后端数据
  • r.Static:提供css/js/img等静态资源
相关推荐
labixiong18 小时前
z-index: 99999 输给 z-index: 2?原生弹窗的 Top Layer 排位战:后进者居上、看得见却点不着
前端·html
芳心粽伙饭18 小时前
HTML第八章 表单标签
前端·html
weixin_4407305018 小时前
pytest结合allure生成html测试报告(step、story、severity、screenshot)
前端·html·pytest·allure报告
用户2986985301419 小时前
在 React 中实现 RTF 与 PDF、HTML 的文档转换实践
javascript·react.js·html
3A Cloud19 小时前
Huashu Design:把 AI Agent 变成一间以 HTML 为画布的设计工作室
前端·人工智能·html
zhanghaha131419 小时前
Python进阶教程:24_Markdown 转 HTML 零基础超详细教程
开发语言·python·html
芳心粽伙饭19 小时前
HTML第七章 表格标签
前端·html
IMPYLH20 小时前
HTML 的 <option> 元素
服务器·数据库·html
平头哥~20 小时前
Day 15 | 不改一行 HTML,给页面加上引号、角标和标签
前端·javascript·css·html·css3·学习资料
Vespeng1 天前
打破传统 MVC:在 Go 中实践高内聚的业务驱动架构
架构·go·gin