新 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{})
}
有疑问加站长微信联系(非本文作者)

Using templates with same name in different directories
官方文档是有看的,我这边用的是两个
index.html
,官方文档用的index.tmpl
,后缀不一样。知道怎么用的,非常感谢:)
https://gitee.com/jalright/ginmultitemplate