关于 Gin 框架加载 html 页面的一点小疑问
新 Gopher
,用 Gin
框架中碰到一些小疑问,已 Google
勿喷。
问题描述
使用 Gin
加载不同文件夹下的 index.html
的一点疑惑,怎么加载不同文件夹下的 index.html
文件。
文件结构:
.
├── main.go
└── templates
├── home
│ └── index.html
└── login
└── index.html
其中 templates/home/index.html
内容为:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Home Title</title>
</head>
<body>
<h1>This is Home page</h1>
</body>
</html>
文件 templates/login/index.html
内容为:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login Title</title>
</head>
<body>
<h1>This is login page</h1>
</body>
</html>
主函数 main.go
文件为:
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func LoginPage(c *gin.Context) {
c.HTML(http.StatusOK, "index.html", gin.H{})
}
func HomePage(c *gin.Context) {
c.HTML(http.StatusOK, "index.html", gin.H{})
}
func main() {
router := gin.Default()
router.LoadHTMLGlob("templates/**/*")
router.GET("/login", LoginPage)
router.GET("/home", HomePage)
router.Run(":8088")
}
发现访问 URL
地址 /login
和 /home
得到相同内容:
这是终端的打印信息:
希望解决的问题是:怎么样访问不同文件夹下的 index.html
文件。
有试过改 main.go
里面的对应函数,没有成功
func LoginPage(c *gin.Context) {
// 之前 c.HTML(http.StatusOK, "index.html", gin.H{})
// 之后:
c.HTML(http.StatusOK, "login/index.html", gin.H{})
}
func IndexPage(c *gin.Context) {
// 之前 c.HTML(http.StatusOK, "index.html", gin.H{})
// 之后:
c.HTML(http.StatusOK, "home/index.html", gin.H{})
}
共 4 个回复
itfzy.cn
看下手册就知道了,手册上有案例
https://gin-gonic.com/zh-cn/docs/examples/html-rendering/
Jaxon
问前是有看的,官方文档里的是
tmpl
后缀,上面问的问题,是访问html
的后缀。感谢楼上两位的回答 @a7a2 @itfzy.cn 👍
Jiang666
请问楼主解决了吗? 文件名好像不能一样 换一个不同的文件名就好了
zsr_cn
2.templates/home/index.html:
templates/login/index.html 可参照修改。
试过可行。